NSURLConnection 的同步方法只需一行就能拿到回傳的 NSData,程式碼非常直觀,適合寫教學或是在背景子執行緒中使用。但絕對不要放在主執行緒——網路延遲會直接凍結整個界面,watchdog 甚至會把你的 App 強制關閉。
- (IBAction)GETSynButtonDidClicked:(UIButton *)sender {
// 網址必須帶 https://
NSString *urlString = @"https://ipad-bjwb.bjd.com.cn/DigitalPublication/publish/Handler/APINewsList.ashx?date=20131129&startRecord=1&len=5&udid=1234567890&terminalType=Iphone&cid=213";
// 網址含中文時需先轉義
urlString = [urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSURL *url = [NSURL URLWithString:urlString];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
NSData *receiveData = [NSURLConnection sendSynchronousRequest:request
returningResponse:nil error:nil];
// 系統內建的 JSON 解析
NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:receiveData
options:NSJSONReadingMutableContainers error:nil];
NSArray *array = dict[@"news"];
self.newsArray = [NSMutableArray array];
for (NSDictionary *smallDict in array) {
NewsModal *modal = [[NewsModal alloc] init];
[modal setValuesForKeysWithDictionary:smallDict];
[self.newsArray addObject:modal];
}
for (NewsModal *modal in self.newsArray) {
NSLog(@"%@", modal.title);
}
}
異步版本把解析邏輯放進 completionHandler,請求發出後立刻返回,主執行緒可以繼續回應使用者操作。記得 queue 傳 [NSOperationQueue mainQueue],這樣回呼才會在主執行緒執行,能安全地更新 UI。
- (IBAction)GETAsyButtonDidClicked:(UIButton *)sender {
NSString *urlString = @"https://ipad-bjwb.bjd.com.cn/DigitalPublication/publish/Handler/APINewsList.ashx?date=20131129&startRecord=1&len=5&udid=1234567890&terminalType=Iphone&cid=213";
NSURL *url = [NSURL URLWithString:urlString];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
[NSURLConnection sendAsynchronousRequest:request
queue:[NSOperationQueue mainQueue]
completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data
options:NSJSONReadingMutableContainers error:nil];
NSArray *array = dict[@"news"];
self.newsArray = [NSMutableArray array];
for (NSDictionary *smallDict in array) {
NewsModal *modal = [[NewsModal alloc] init];
[modal setValuesForKeysWithDictionary:smallDict];
[self.newsArray addObject:modal];
}
for (NewsModal *modal in self.newsArray) {
NSLog(@"%@", modal.title);
}
}];
}
第一,回傳的 error 參數在原範例中被寫成 nil,這是絕對要避免的習慣。網路請求失敗是很正常的事,不處理錯誤就會出現難以追查的空白畫面。
第二,JSONObjectWithData:options:error: 的 error 也必須接收並判斷,伺服器回傳非 JSON(例如 HTML 錯誤頁)時會直接回 nil。
第三,NSURLConnection 從 iOS 9 起已被標記為廢棄,且預設會被 App Transport Security 阻擋非 HTTPS 連線。新專案應改用 NSURLSession,並在 Info.plist 中說明例外域名。
NSURLSessionDataTask *task = [[NSURLSession sharedSession]
dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
// 處理結果
}];
[task resume];
最後別忘了在異步回呼中若拿到的是新資料,記得呼叫 [self.tableView reloadData],否則畫面不會更新。