您的位置:首页 > 编程语言 > PHP开发

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

2013-08-26 19:56 716 查看
在使用的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 = [[NSString
alloc]initWithFormat:@"http://ip/logincheck.php?us=%@&ps=%@",m_tf_userName.text,m_tf_password.text];
   
NSURL *url = [[NSURL
alloc]initWithString:s_url];

    //创建请求对象
   
m_data = [[NSMutableData
alloc]init];
   
NSURLRequest *request = [[NSURLRequest
alloc]initWithURL:url];

    [[NSURLConnection
alloc]initWithRequest:request
delegate:self];

    
 }

//接收数据,实现了NSURLConnectionDelegate协议的方法
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData
*)data
{
    [m_data
appendData:data];
}

//数据接收完成,实现了NSURLConnectionDelegate协议的方法
- (void)connectionDidFinishLoading:(NSURLConnection *)connectio
{

    NSString *s_result = [[NSString
alloc]initWithData:m_data
encoding:NSUTF8StringEncoding];

    //处理接收到的数据

    //如果包含“ok”,则登录成功,反之则失败
   
if ([s_result rangeOfString:@"ok"].length>0)
    {

        UIAlertView *alert =[[UIAlertView
alloc]initWithTitle:@"login result"
message:@"login success!"
delegate:self
cancelButtonTitle:@"ok"
otherButtonTitles: nil];
        [alert
show];
    }
   
else
    {

        UIAlertView *alert =[[UIAlertView
alloc]initWithTitle:@"login result"
message:@"login faile!"
delegate:self
cancelButtonTitle:@"ok"
otherButtonTitles: nil];
        [alert
show];

        NSLog(@"login faile");
    }
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息