您的位置:首页 > 其它

NSURLSession之get请求模拟登录

2017-08-14 00:45 211 查看

get请求模拟登录

- (IBAction)login:(id)sender {

    

    // 0.请求地址

    NSString *URLString = [NSString stringWithFormat:@"http://localhost/php/login/login.php?username=%@&password=%@",self.usernameTextField.text,self.passwordTextField.text];

    

    // 0.1 当GET请求的URL中有中文时,需要使用百分号转义(URLQueryAllowedCharacterSet
: 允许URL里面的查询字符串进行百分号转义)

    URLString = [URLString stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];

    

    // 1.URL

    NSURL *URL = [NSURL URLWithString:URLString];

    

    // 2.获取单例session,发起和启动任务

    [[[NSURLSession sharedSession] dataTaskWithURL:URL completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error)
{

        

        // 3.错误处理

        if (error == nil) {

            

            // 4.反序列化

            NSDictionary *result = [NSJSONSerialization JSONObjectWithData:data options:0 error:NULL];

            // 5.判断登录是否成功

            if ([result[@"state"] isEqualToString:@"OK"])
{

                NSLog(@"登录成功");

            } else {

                NSLog(@"登录失败");

            }

            

        } else {

            NSLog(@"%@",error);

        }

        

    }] resume];

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: