IOS之网络
一、NSURLConnection
1.简单登陆(get请求)
#import "MBProgressHUD+MJ.h"
@interface HMViewController () <NSURLConnectionDataDelegate>
@property (weak, nonatomic) IBOutlet UITextField *usernameField;
@property (weak, nonatomic) IBOutlet UITextField *pwdField;
- (IBAction)login;
/**
* 用来存放服务器返回的所有数据
*/
@property (nonatomic, strong) NSMutableData *responseData;
@end
@implementation HMViewController
- (void)viewDidLoad
{
[super viewDidLoad];
}
/**
* 登录逻辑
*/
- (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.200: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];
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 connectionWithRequest:request delegate:self];
// [[NSURLConnection alloc] initWithRequest:request delegate:self];
// [[NSURLConnection alloc] initWithRequest:request delegate:self startImmediately:YES];
NSURLConnection *conn4 = [[NSURLConnection alloc] initWithRequest:request delegate:self startImmediately:NO];
[conn4 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:@"网络繁忙, 请稍后再试"];
}
}];
}
2.简单登陆(post请求)
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。