想讓 App 抓取網路資料時不卡住畫面?非同步是必備技能。實作非同步抓取有幾種常見方式,本章先聚焦在如何使用 ASIHTTPRequest 這個好用的第三方類,完成網路請求。
如果使用同步方式抓取網路資料,在主線程上會讓整個介面「凍住」,使用者體驗極差。把請求丟到背景執行、完成後再回來更新 UI,才是正確做法。實作非同步抓取,最簡單的入門方式有兩種:一是用 ASIHTTPRequest,二是用 MBProgressHUD。本章先講前者。
使用 ASIHTTPRequest 前,需要先引入相關類,這裡我們採用 ASIFormDataRequest,記得引用標頭檔 ASIFormDataRequest.h。為了方便管理位址,我在 GetWebInfo 類裡定義了一個 NSString 型別的 mywebaddress 屬性來存放網址。
#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];
}
程式碼出乎意料地簡單——一個成功回呼、一個失敗回呼,就搞定了非同步抓取。透過 startAsynchronous 觸發請求,成功時在 requestFinished: 解析 JSON 並刷新列表,失敗時在 requestFailed: 提示使用者。本章內容雖少,卻非常實用,趕快動手試試吧。