NSURLSession
代理方法
有的时候,我们可能需要监听网络请求的过程(如下载文件需监听文件下载进度),那么就需要用到代理方法。

1 #import "ViewController.h" 2 3 @interface ViewController ()<NSURLSessionDataDelegate> 4 @property (nonatomic, strong) NSMutableData *responseData; 5 @end 6 7 @implementation ViewController 8 9 -(NSMutableData *)responseData 10 { 11 if (_responseData == nil) { 12 _responseData = [NSMutableData data]; 13 } 14 return _responseData; 15 } 16 17 //当点击控制器View的时候会调用该方法 18 -(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event 19 { 20 [self delegateTest]; 21 } 22 23 //发送请求,代理方法 24 -(void)delegateTest 25 { 26 //1.确定请求路径 27 NSURL *url = [NSURL URLWithString:@"http://120.25.226.186:32812/login?username=520it&pwd=520it&type=JSON"]; 28 29 //2.创建请求对象 30 //请求对象内部默认已经包含了请求头和请求方法(GET) 31 NSURLRequest *request = [NSURLRequest requestWithURL:url]; 32 33 //3.获得会话对象,并设置代理 34 /* 35 第一个参数:会话对象的配置信息defaultSessionConfiguration 表示默认配置 36 第二个参数:谁成为代理,此处为控制器本身即self 37 第三个参数:队列,该队列决定代理方法在哪个线程中调用,可以传主队列|非主队列 38 [NSOperationQueue mainQueue] 主队列: 代理方法在主线程中调用 39 [[NSOperationQueue alloc]init] 非主队列: 代理方法在子线程中调用 40 */ 41 NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration] delegate:self delegateQueue:[NSOperationQueue mainQueue]]; 42 43 //4.根据会话对象创建一个Task(发送请求) 44 NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request]; 45 46 //5.执行任务 47 [dataTask resume]; 48 } 49 50 //1.接收到服务器响应的时候调用该方法 51 -(void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveResponse:(NSURLResponse *)response completionHandler:(void (^)(NSURLSessionResponseDisposition))completionHandler 52 { 53 //在该方法中可以得到响应头信息,即response 54 NSLog(@"didReceiveResponse--%@",[NSThread currentThread]); 55 56 //注意:需要使用completionHandler回调告诉系统应该如何处理服务器返回的数据 57 //默认是取消的 58 /* 59 NSURLSessionResponseCancel = 0, 默认的处理方式,取消 60 NSURLSessionResponseAllow = 1, 接收服务器返回的数据 61 NSURLSessionResponseBecomeDownload = 2,变成一个下载请求 62 NSURLSessionResponseBecomeStream 变成一个流 63 */ 64 65 completionHandler(NSURLSessionResponseAllow); 66 } 67 68 //2.接收到服务器返回数据的时候会调用该方法,如果数据较大那么该方法可能会调用多次 69 -(void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveData:(NSData *)data 70 { 71 NSLog(@"didReceiveData--%@",[NSThread currentThread]); 72 73 //拼接服务器返回的数据 74 [self.responseData appendData:data]; 75 } 76 77 //3.当请求完成(成功|失败)的时候会调用该方法,如果请求失败,则error有值 78 -(void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error 79 { 80 NSLog(@"didCompleteWithError--%@",[NSThread currentThread]); 81 82 if(error == nil) 83 { 84 //解析数据,JSON解析请参考http://www.cnblogs.com/wendingding/p/3815303.html 85 NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:self.responseData options:kNilOptions error:nil]; 86 NSLog(@"%@",dict); 87 } 88 } 89 @end