1. 程式人生 > >蘋果自帶API:Foundation——NSURLConnection

蘋果自帶API:Foundation——NSURLConnection

要監聽伺服器返回的data,所以使用<NSURLConnectionDataDelegate>協議

 #pragma mark- NSURLConnectionDataDelegate代理方法
 
 //當接收到伺服器的響應(連通了伺服器)時會呼叫
 
 -(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
 
 //當接收到伺服器的資料時會呼叫(可能會被呼叫多次,每次只傳遞部分資料)
 
 -(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
 
 //當伺服器的資料載入完畢時就會呼叫
 
 -(void)connectionDidFinishLoading:(NSURLConnection *)connection
 
 //請求錯誤(失敗)的時候呼叫(請求超時\斷網\沒有網\,一般指客戶端錯誤)
 
 -(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
 //
 37 //   2.1設定請求路徑
 38     NSString *urlStr=[NSString stringWithFormat:@"http://192.168.1.53:8080/MJServer/login?username=%@&pwd=%@",self.username.text,self.pwd.text];
 39     NSURL *url=[NSURL URLWithString:urlStr];
 40     
 41 //   2.2建立請求物件
 42 //    NSURLRequest *request=[NSURLRequest requestWithURL:url];//預設就是GET請求
 43     //設定請求超時
 44     NSMutableURLRequest *request=[NSMutableURLRequest  requestWithURL:url];
 45     request.timeoutInterval=5.0;
 46     
 47 //   2.3.傳送請求
 48  //使用代理髮送非同步請求(通常應用於檔案下載)
 49     NSURLConnection *conn=[NSURLConnection connectionWithRequest:request delegate:self];
 50     [conn start];
 51     NSLog(@"已經發出請求---");
 52 }
 53 
 54 #pragma mark- NSURLConnectionDataDelegate代理方法
 55 /*
 56  *當接收到伺服器的響應(連通了伺服器)時會呼叫
 57  */
 58 -(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
 59 {
 60     NSLog(@"接收到伺服器的響應");
 61     //初始化資料
 62     self.responseData=[NSMutableData data];
 63 }
 64 
 65 /*
 66 *當接收到伺服器的資料時會呼叫(可能會被呼叫多次,每次只傳遞部分資料)
 67 */
 68 -(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
 69 {
 70     NSLog(@"接收到伺服器的資料");
 71     //拼接資料
 72     [self.responseData appendData:data];
 73         NSLog(@"%d---%@--",self.responseData.length,[NSThread currentThread]);
 74 }
 75 
 76 /*
 77  *當伺服器的資料載入完畢時就會呼叫
 78  */
 79 -(void)connectionDidFinishLoading:(NSURLConnection *)connection
 80 {
 81     NSLog(@"伺服器的資料載入完畢");
 82     //隱藏HUD
 83     [MBProgressHUD hideHUD];
 84     
 85     //處理伺服器返回的所有資料
 86     NSDictionary *dict=[NSJSONSerialization JSONObjectWithData:self.responseData options:NSJSONReadingMutableLeaves error:nil];
 87     
 88     //判斷後,在介面提示登入資訊
 89     NSString *error=dict[@"error"];
 90     if (error) {
 91         [MBProgressHUD showError:error];
 92     }else
 93     {
 94         NSString *success=dict[@"success"];
 95         [MBProgressHUD showSuccess:success];
 96     }
 97     NSLog(@"%d---%@--",self.responseData.length,[NSThread currentThread]);
 98 }
 99 /*
100  *請求錯誤(失敗)的時候呼叫(請求超時\斷網\沒有網\,一般指客戶端錯誤)
101  */
102 -(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
103 {
104 //     NSLog(@"請求錯誤");
105     //隱藏HUD
106     [MBProgressHUD hideHUD];
107     [MBProgressHUD showError:@"網路繁忙,請稍後重試!"];
108 }
109 @end