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>
您可在下列課程中了解更多技巧喔!
相關學習資源
【ObjectiveC】Objective-C程式語言