码迷,mamicode.com
首页 > 移动开发 > 详细

IOS网络第二天 - 02-异步HTTP请求block回调 解析

时间:2015-09-14 15:25:46      阅读:224      评论:0      收藏:0      [点我收藏+]

标签:

**************

#import "HMViewController.h"
#import "MBProgressHUD+MJ.h"

@interface HMViewController ()
@property (weak, nonatomic) IBOutlet UITextField *username;
@property (weak, nonatomic) IBOutlet UITextField *pwd;
- (IBAction)login;
@end

@implementation HMViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
}

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    [self.view endEditing:YES];
}

- (IBAction)login {
    // 1.用户名
    NSString *usernameText = self.username.text;
    if (usernameText.length == 0) {
        [MBProgressHUD showError:@"请输入用户名"];
        return;
    }
    
    // 2.密码
    NSString *pwdText = self.pwd.text;
    if (pwdText.length == 0) {
        [MBProgressHUD showError:@"请输入密码"];
        return;
    }
    
    // 3.发送用户名和密码给服务器(走HTTP协议)
    // 创建一个URL : 请求路径
    NSString *urlStr = [NSString stringWithFormat:@"http://localhost:8080/MJServer/login?username=%@&pwd=%@",usernameText, pwdText];
    NSURL *url = [NSURL URLWithString:urlStr];
    
    // 创建一个请求
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
//    NSLog(@"begin---");
    
    // 发送一个异步请求(在主线程发送请求)
    // queue :存放completionHandler这个任务
    NSOperationQueue *queue = [NSOperationQueue mainQueue];
    [NSURLConnection sendAsynchronousRequest:request queue:queue completionHandler:
     ^(NSURLResponse *response, NSData *data, NSError *connectionError) {
        // 这个block会在请求完毕的时候自动调用
        if (connectionError || data == nil) {
            [MBProgressHUD showError:@"请求失败"];
            return;
        }
        
        // 解析服务器返回的JSON数据
        NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
        NSString *error = dict[@"error"];
        if (error) {
            // {"error":"用户名不存在"}
            // {"error":"密码不正确"}
            [MBProgressHUD showError:error];
        } else {
            // {"success":"登录成功"}
            NSString *success = dict[@"success"];
            [MBProgressHUD showSuccess:success];
        }
     }];
    
//    NSLog(@"end---");
}
@end

 

IOS网络第二天 - 02-异步HTTP请求block回调 解析

标签:

原文地址:http://www.cnblogs.com/ios-g/p/4807006.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!