在 iOS 9 中使用 NSURLSession API 與後台資料交換

作者:戴谷州
精誠資訊 恆逸教育訓練中心 資深講師
技術分類:程式設計

 App與後台溝通是很重要的功能之一,在 iOS 9版本開始,關於網路溝通的API有一些異動,將使用NSURLSeesion與NSURLSessionTask取代NSURLConnection。

使用NSURLConnection的程式碼如下:

NSString * postLink = @"http://ikenapp.appspot.com/json/postProductsByCategory.jsp";
NSString * queryString = @"cateId=2";
-(void) getWithNSURLConnectionAsyc{
//Request Line
NSMutableURLRequest * req = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:postLink]];
req.HTTPMethod = @"POST";
//Request Body
req.HTTPBody = [queryString dataUsingEncoding:NSUTF8StringEncoding];
[NSURLConnection sendAsynchronousRequest:req queue:[NSOperationQueue mainQueue]
 completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable   
 connectionError) {
if(connectionError){
NSLog(@"connectionError : %@",connectionError);
return;
}
NSLog(@"RESULT : \n%@", [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]);
}];
}


使用NSURLSeesion與NSURLSessionTask程式碼如下:

-(void) getWithNSURLSession{
//Request Line
NSMutableURLRequest * req = [NSMutableURLRequest requestWithURL:
 [NSURL URLWithString:postLink]];
req.HTTPMethod = @"POST";
//Request Body
req.HTTPBody = [queryString dataUsingEncoding:NSUTF8StringEncoding];
NSURLSession * session = [NSURLSession sharedSession];
NSURLSessionTask * task = [ session dataTaskWithRequest:req completionHandler:^(NSData *
 _Nullable data, NSURLResponse * _Nullable response,
 NSError * _Nullable error) {
if(error){
NSLog(@"SESSION Error : %@",error);
return;
}
NSLog(@"SESSION RESULT : \n%@", [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]);
}];
[task resume];
}

從iOS 9版本開始,非https連線需要在Info.plist做下列設定,程式才可以正常執行:

<key>NSAppTransportSecurity </key>
<dict>
<key>NSAllowsArbitraryLoads </key>
<true/>
</dict>