網絡請求(I)

NSURLSession

代理方法

有的時候,咱們可能須要監聽網絡請求的過程(以下載文件需監聽文件下載進度),那麼就須要用到代理方法。html

 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
View Code

 

 

 

 

 

 

 

 

 

 

參考資料:NSURLConnection從入門到放棄服務器

相關文章
相關標籤/搜索