您的位置:首页 > 其它

75 NSURLConnection的基本使用示例

2015-08-31 00:38 323 查看
1>NSURLConnection的基本使用示例:

/**
*  登录逻辑
*/
- (IBAction)login
{
// 1.表单验证(输入验证)
NSString *username = self.usernameField.text;
if (username.length == 0) { // 没有输入用户名
//        [MBProgressHUD showError:@"请输入用户名"];
return;
}

NSString *pwd = self.pwdField.text;
if (pwd.length == 0) { // 没有输入密码
//        [MBProgressHUD showError:@"请输入密码"];
return;
}

// 弹框
//    [MBProgressHUD showMessage:@"正在拼命登录中..."];

// 2.发送请求给服务器(带上帐号和密码)
// GET请求:请求行\请求头

// 2.1.设置请求路径
NSString *urlStr = [NSString stringWithFormat:@"http://192.168.1.101:8080/MJServer/login?username=%@&pwd=%@", username, pwd];

// 转码
urlStr = [urlStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];

// URL里面不能包含中文
NSURL *url = [NSURL URLWithString:urlStr];

// 2.2.创建请求对象
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url]; // 默认就是GET请求
request.timeoutInterval = 5; // 设置请求超时

// 2.3.发送请求
//    [self sendAsync:request];
NSURLConnection *c = [NSURLConnection connectionWithRequest:request delegate:self];

NSLog(@"---------已经发出请求");
}

#pragma mark - NSURLConnectionDataDelegate 代理方法
/**
*  请求错误(失败)的时候调用(请求超时\断网\没有网, 一般指客户端错误)
*/
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
NSLog(@"connection:didFailWithError:");
//    [MBProgressHUD hideHUD];
//
//    [MBProgressHUD showError:@"网络繁忙, 请稍后再试"];
}

/**
*  当接受到服务器的响应(连通了服务器)就会调用
*/
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
NSLog(@"connection:didReceiveResponse:");

// 初始化数据
self.responseData = [NSMutableData data];

}

/**
*  当接受到服务器的数据就会调用(可能会被调用多次, 每次调用只会传递部分数据)
*/
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
NSLog(@"connection:didReceiveData:");

// 拼接(收集)数据
[self.responseData appendData:data];
}

/**
*  当服务器的数据接受完毕后就会调用
*/
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSLog(@"connectionDidFinishLoading:");

// 隐藏HUD
[MBProgressHUD hideHUD];

// 解析服务器返回的数据
NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:self.responseData options:NSJSONReadingMutableLeaves error:nil];
NSString *error =  dict[@"error"];
if (error) { // 登录失败
[MBProgressHUD showError:error];
} else { // 登录成功
NSString *success =  dict[@"success"];
//        [MBProgressHUD showSuccess:success];
}
}

/**
*  发送异步请求的方式2: start方法, 代理
*/
- (void)sendAsync2:(NSURLRequest *)request
{
NSURLConnection *conn = [NSURLConnection connectionWithRequest:request delegate:self];
[conn start]; // 异步执行
}

/**
*  发送异步请求的方式1: 类方法, block
*/
- (void)sendAsync:(NSURLRequest *)request
{
NSOperationQueue *queue = [NSOperationQueue mainQueue];
[NSURLConnection sendAsynchronousRequest:request queue:queue completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {  // 当请求结束的时候调用 (拿到了服务器的数据, 请求失败)

// 隐藏HUD (刷新UI界面, 一定要放在主线程, 不能放在子线程)
[MBProgressHUD hideHUD];

/**
解析data :
{"error":"用户名不存在"}
{"error":"密码不正确"}
{"success":"登录成功"}
*/
if (data) { // 请求成功
NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
NSString *error = dict[@"error"];
if (error) { // 登录失败
//                [MBProgressHUD showError:error];
} else { // 登录成功
NSString *success =  dict[@"success"];
//                [MBProgressHUD showSuccess:success];
}
} else { // 请求失败
//            [MBProgressHUD showError:@"网络繁忙, 请稍后再试"];
}
}];
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: