要實作異步抓取,最省事的做法有兩種:一是用 ASIHTTPRequest,二是用 MBProgressHUD。本章先講前者。
ASIHTTPRequest 是 iOS 早期最流行的第三方網路庫(如今已被 AFNetworking 與 NSURLSession 取代,但理解它的 delegate 模型仍有價值)。使用前需引入 ASIFormDataRequest.h。
我在 GetWebInfo 類別中定義了一個 NSString 屬性 mywebaddress 用來集中管理位址,如此一來切換環境時不必到處找 URL。
#pragma mark
#pragma mark 異步載入資料
// 初始化資料,異步載入
- (void)initListData {
GetWebInfo *getwebinfo = [[GetWebInfo alloc] init];
NSURL *url = [NSURL URLWithString:getwebinfo.mywebaddress];
ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url];
NSString *mypage = [NSString stringWithFormat:@"%d", _page];
[request addPostValue:@"GetNewsbyPage" forKey:@"Method"];
[request addPostValue:@"公共新聞" forKey:@"type"];
[request addPostValue:@"4" forKey:@"rows"];
[request addPostValue:mypage forKey:@"page"];
[request setDelegate:self];
[request startAsynchronous];
}
成功與失敗各有一個回呼:
// 異步載入成功
- (void)requestFinished:(ASIHTTPRequest *)request {
NSData *responseData = [request responseData];
NSArray *keys = [NSJSONSerialization JSONObjectWithData:responseData
options:NSJSONReadingMutableContainers
error:nil];
allcount = [[keys valueForKey:@"total"] integerValue];
[self.list addObject:[keys valueForKey:@"rows"]];
[_tableView reloadData];
}
// 異步載入失敗
- (void)requestFailed:(ASIHTTPRequest *)request {
NSError *error = [request error];
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示訊息!"
message:@"載入資料失敗!網路連線失敗!"
delegate:nil
cancelButtonTitle:@"確定"
otherButtonTitles:nil];
[alert show];
}
程式碼就是這麼簡單:一個成功方法、一個失敗方法。真正需要留意的是回呼所處的執行緒——ASIHTTPRequest 預設會把回呼調回主線程,因此可以直接在 requestFinished: 中 reloadData 而不必額外做 thread hop。這點與 NSURLConnection 的 delegate 行為不同,遷移程式碼時經常被忽略。
另外要提醒,ASIHTTPRequest 早已停止維護,新專案請改用 NSURLSession。上面 requestFailed: 中宣告的 error 變數若未使用,新版編譯器會產生警告,實作時記得實際用它記錄或顯示錯誤原因。