iOS9.0之後NSURLConnection被登出,採用NSURLSession,先介紹NSURLSession,然後介紹NSURLConnection
1.NSURLSession:
post請求:
//1. NSMutableURLRequest *request=[NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http://www.baidu.com"]]; request.HTTPMethod=@"POST"; request.HTTPBody = [@"" dataUsingEncoding:NSUTF8StringEncoding]; //2. NSURLSession *session=[NSURLSession sharedSession]; NSURLSessionDataTask *dataTask= [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) { NSLog(@"NSURLSession載入資料。。。。post。。。。。%@",data); }]; //3. [dataTask resume];
建立請求並設定代理delegate:(NSURLSessionDataDelegate)
//1.確定請求路徑 NSURL *url = [NSURL URLWithString:@"http://www.baidu.com"]; //2.建立請求物件 //請求物件內部預設已經包含了請求頭和請求方法(GET) NSURLRequest *request = [NSURLRequest requestWithURL:url]; //3.獲得會話物件,並設定代理 /* 第一個引數:會話物件的配置資訊defaultSessionConfiguration 表示預設配置 第二個引數:誰成為代理,此處為控制器本身即self 第三個引數:佇列,該佇列決定代理方法在哪個執行緒中呼叫,可以傳主佇列|非主佇列 [NSOperationQueue mainQueue] 主佇列: 代理方法在主執行緒中呼叫 [[NSOperationQueue alloc]init] 非主佇列: 代理方法在子執行緒中呼叫 */ NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration] delegate:self delegateQueue:[NSOperationQueue mainQueue]]; //4.根據會話物件建立一個Task(傳送請求) NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request]; //5.執行任務 [dataTask resume];
delegate協議方法:
//1.接收到伺服器響應的時候呼叫該方法 -(void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveResponse:(NSURLResponse *)response completionHandler:(void (^)(NSURLSessionResponseDisposition))completionHandler{ //在該方法中可以得到響應頭資訊,即response NSLog(@"didReceiveResponse--%@",[NSThread currentThread]); completionHandler(NSURLSessionResponseAllow); //注意:需要使用completionHandler回撥告訴系統應該如何處理伺服器返回的資料 //預設是取消的 /* NSURLSessionResponseCancel = 0, 預設的處理方式,取消 NSURLSessionResponseAllow = 1, 接收伺服器返回的資料 NSURLSessionResponseBecomeDownload = 2,變成一個下載請求 NSURLSessionResponseBecomeStream 變成一個流 */ } //2.接收到伺服器返回資料的時候會呼叫該方法,如果資料較大那麼該方法可能會呼叫多次 -(void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveData:(NSData *)data{ NSLog(@"didReceiveData--%@",[NSThread currentThread]); //拼接伺服器返回的資料 } //3.當請求完成(成功|失敗)的時候會呼叫該方法,如果請求失敗,則error有值 -(void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error { NSLog(@"didCompleteWithError--%@",[NSThread currentThread]); if(error == nil) { //解析資料,JSON解析請參考 } }
2.NSURLConnection
普通請求:
/* //1.網址 NSURL *url=[NSURL URLWithString:@"http://www.baidu.com"]; //2.請求 NSURLRequest *request=[NSURLRequest requestWithURL:url]; //3.佇列 NSOperationQueue *queue=[[NSOperationQueue alloc]init]; //4.傳送非同步請求 [NSURLConnection sendAsynchronousRequest:request queue:queue completionHandler:^(NSURLResponse * response, NSData * data, NSError * connectionError) { NSString *content=[[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding]; NSLog(@"載入成功:%@",content); }]; */ //同步傳送,要放到另一個執行緒裡,防止阻塞; dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{ NSURLRequest *request=[NSURLRequest requestWithURL:[NSURL URLWithString:@"http://www.baidu.com"]]; NSURLResponse *response; NSData *data=[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:nil];//&指的是指標; NSString *content=[[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding]; NSLog(@"NSURLConnection載入資料。。。。。。。:%@",content); });
代理請求:(NSURLConnectionDataDelegate)
NSURLRequest *request=[NSURLRequest requestWithURL:[NSURL URLWithString:@"http://www.baidu.com"]]; // NSURLResponse *response; [NSURLConnection connectionWithRequest:request delegate:self];
代理協議方法:
// -(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response{ NSLog(@"接到response"); }
// -(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{ NSLog(@"接收資料"); }
// -(void)connectionDidFinishLoading:(NSURLConnection *)connection{ NSLog(@"接收資料完成"); }