ASIHttpRequest 是早期 iOS 開發中常見的第三方網路庫。它的優點是 API 直接、程式碼量少,適合快速完成 GET 或 POST 請求,並取得 JSON 資料。
使用 ASIHttpRequest 時,除了加入程式庫,還需要匯入相關系統框架,例如 MobileCoreServices、SystemConfiguration、CFNetwork 與 libz。此外,若專案使用 ARC,通常要為 ASIHTTPRequest 相關檔案加上 fno-objc-arc 編譯旗標。
以下範例展示如何建立 URL、送出請求,並在完成區塊中解析回傳的 JSON。
NSURL *url = [NSURL URLWithString:@"https://api.kuaidi100.com/api?id=d6b9888b0da96f6b"];
ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
[request setCompletionBlock:^{
NSError *error = nil;
NSDictionary *dictionary = [NSJSONSerialization JSONObjectWithData:request.responseData options:kNilOptions error:&error];
NSArray *arr = [dictionary objectForKey:@"data"];
for (NSDictionary *temp in arr) {
NSLog(@"%@ %@", [temp objectForKey:@"time"], [temp objectForKey:@"context"]);
}
}];
[request setFailedBlock:^{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"網路連線異常,請稍後再試" delegate:nil cancelButtonTitle:@"退出" otherButtonTitles:nil];
[alert show];
}];
[request startAsynchronous];使用這類舊網路庫時,要特別注意 callback 執行緒、資料解析錯誤處理,以及請求失敗時的使用者提示。若為新專案,通常會改用 URLSession 或 AFNetworking、Alamofire 等工具。