ios异步登录,登录的是php写服务器,同理可以实现文件图片下载

来源:互联网 发布:快彩网彩票php源码 编辑:程序博客网 时间:2024/05/29 09:29

在使用的viewController的.h文件里实现以下协议 

<NSURLConnectionDataDelegate,NSURLConnectionDelegate>


注:logincheck.php的内容为

<?php
  $username = $_GET["us"];
  $password = $_GET["ps"];
  if($username =="he"&&  $password =="he")
  {
  echo "login ok!!!";
  }
  else
  {
echo "oh no ! you must try again!";
  }
?>


//异步登录

- (IBAction)btnAsyLogin:(id)sender {

    //创建url,因为此代码是在本地测试的,所以ip为127.0.0.1,服务器为Apache

    NSString * s_url = [[NSStringalloc]initWithFormat:@"http://ip/logincheck.php?us=%@&ps=%@",m_tf_userName.text,m_tf_password.text];

   NSURL *url = [[NSURLalloc]initWithString:s_url];

    //创建请求对象

   m_data = [[NSMutableDataalloc]init];

   NSURLRequest *request = [[NSURLRequestalloc]initWithURL:url];

    [[NSURLConnectionalloc]initWithRequest:requestdelegate:self];

    

 }

//接收数据,实现了NSURLConnectionDelegate协议的方法

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data

{

    [m_dataappendData:data];

}

//数据接收完成,实现了NSURLConnectionDelegate协议的方法

- (void)connectionDidFinishLoading:(NSURLConnection *)connectio

{

    NSString *s_result = [[NSStringalloc]initWithData:m_dataencoding:NSUTF8StringEncoding];

    //处理接收到的数据

    //如果包含“ok”,则登录成功,反之则失败

   if ([s_result rangeOfString:@"ok"].length>0)

    {

        UIAlertView *alert =[[UIAlertViewalloc]initWithTitle:@"login result"message:@"login success!"delegate:selfcancelButtonTitle:@"ok"otherButtonTitles: nil];

        [alertshow];

    }

   else

    {

        UIAlertView *alert =[[UIAlertViewalloc]initWithTitle:@"login result"message:@"login faile!"delegate:selfcancelButtonTitle:@"ok"otherButtonTitles: nil];

        [alertshow];

        NSLog(@"login faile");

    }

}

原创粉丝点击