ASIHTTPRequest 是一套廣為使用的第三方網路庫,能大幅精簡程式碼、提升開發效率。本文示範如何整合它並完成一個非同步的 POST 請求。
一、匯入第三方庫 ASIHTTPRequest。
二、整合後往往會出現大量編譯錯誤,原因通常有兩個:一是缺少 Xcode 自帶的幾個系統framework;二是該庫並未使用 ARC(自動引用計數)。
三、解決方案:
MobileCoreServices.framework、SystemConfiguration.framework、CFNetwork.framework 與 libz.1.2.5.dylib。-fno-objc-arc 旗標。
#import "ASIHTTPRequest.h"
- (void)viewDidLoad {
[super viewDidLoad];
[self requestHttp];
}
- (void)requestHttp {
// 建立 URL 物件
NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:
@"https://api.kuaidi100.com/api?id=d6b9888b0da96f6b&com=%@&nu=%@&show=0&muti=1&order=desc&display=mobile"]];
NSLog(@"url======%@", url);
// 建立請求物件
ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
// 送出請求,並在完成區塊中處理返回的 JSON 資料
[request setCompletionBlock:^{
NSError *error = nil;
// 以字典接收返回的 JSON 資料
NSDictionary *dictionary = [NSJSONSerialization JSONObjectWithData:request.responseData
options:kNilOptions
error:&error];
NSLog(@"%@", dictionary);
// 取出 data 欄位並放入陣列
NSArray *arr = [dictionary objectForKey:@"data"];
// 遍歷並整理每一筆資料
for (NSDictionary *temp in arr) {
[self.array addObject:[NSString stringWithFormat:@"%@ /n%@",
[temp objectForKey:@"time"], [temp objectForKey:@"context"]]];
}
// 將整理後的資料組合成字串
for (NSString *temp in self.array) {
[self.mutableString appendString:[NSString stringWithFormat:@"%@/n", temp]];
NSLog(@"temp==== %@", temp);
}
// 將結果字串賦值給 Label 顯示
self.jieGuoLale.text = self.mutableString;
NSLog(@"self.jieGuoLale.text======%@", self.jieGuoLale.text);
}];
// 若請求失敗,彈出警示框
[request setFailedBlock:^{
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"提示"
message:@"問題警告:網路連結異常,請稍後再試"
delegate:nil
cancelButtonTitle:@"退出"
otherButtonTitles:nil];
[alertView show];
}];
// 送出一個非同步請求
[request startAsynchronous];
}
透過 setCompletionBlock: 與 setFailedBlock: 分別處理成功與失敗的情境,再呼叫 startAsynchronous 即可在背景執行請求,避免阻塞主執行緒。相較於原生 API,ASIHTTPRequest 讓整個流程更加直覺簡潔。