在 AFNetworking 普及之前,ASIHTTPRequest 幾乎是 iOS 網路層的標準答案。它是個相當好用的開源 HTTP 組件,能大幅減少樣板程式碼,功能涵蓋異步請求、佇列請求、快取、斷點續傳、進度追蹤、檔案上傳與 HTTP 認證,並且支援 Objective-C 的 Block 語法。官方網站:https://allseeing-i.com/ASIHTTPRequest/
需要留意的是,這個庫早已停止維護,新專案建議改用 AFNetworking 或原生 URLSession;但維護老專案時仍常會碰到,因此值得留一份筆記。
需要引入的 Framework:
CFNetwork.framework
SystemConfiguration.framework
MobileCoreServices.framework
libz.dylib
ASI 不支援 ARC。如果你的專案啟用了 ARC,需要讓兩者混編,只要對非 ARC 的檔案加上 -fno-objc-arc 編譯標記即可。
- (IBAction)UpLoad:(UIButton *)sender {
NSURL *url = [NSURL URLWithString:@"https://localhost:8080/UploadServer/UploadServlet"];
ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url];
[request setRequestMethod:@"POST"];
// 方法一:適合小檔案,先轉成 NSData 再放進 POST body
NSData *dataImage = UIImageJPEGRepresentation([UIImage imageNamed:@"1.jpg"], 1);
[request appendPostData:dataImage];
// 方法二:直接從檔案路徑讀入,同樣適合小檔案
[request appendPostDataFromFile:[[NSBundle mainBundle] pathForResource:@"1" ofType:@"jpg"]];
// 方法三:串流上傳,檔案大小不限
// setShouldStreamPostDataFromDisk 預設為 NO,需手動開啟
[request setShouldStreamPostDataFromDisk:YES];
[request setPostBodyFilePath:[[NSBundle mainBundle] pathForResource:@"1" ofType:@"jpg"]];
[request startAsynchronous];
}
方法一與方法二會先把整個檔案讀進記憶體,遇到大檔容易 OOM;方法三走磁碟串流,是上傳大檔案時的正確選擇。
- (IBAction)downLoad:(UIButton *)sender {
// 避免重複點擊產生不受控的請求
if (_request != nil) {
return;
}
// 已下載完成就不再重跑
if ([[NSFileManager defaultManager] fileExistsAtPath:[self getFilePath]]) {
return;
}
NSString *string = @"https://localhost:8080/downloadSrver/xcode_6.dmg.dmg";
string = [string stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSURL *url = [NSURL URLWithString:string];
_request = [ASIHTTPRequest requestWithURL:url];
// 最終存放路徑
[_request setDownloadDestinationPath:[self getFilePath]];
// 下載進度代理
[_request setDownloadProgressDelegate:self];
// 必須設定,否則無法續傳
[_request setAllowResumeForFileDownloads:YES];
// 下載過程中先寫入暫存檔,完成後才搬移到目標路徑
[_request setTemporaryFileDownloadPath:[self getTemoPath]];
_request.delegate = self;
_request.downloadProgressDelegate = self;
[_request startAsynchronous];
}
- (IBAction)pause:(UIButton *)sender {
// 取消請求並清除代理
[_request clearDelegatesAndCancel];
_request = nil;
}
- (NSString *)getTemoPath {
return [NSTemporaryDirectory() stringByAppendingPathComponent:@"temp"];
}
- (NSString *)getFilePath {
NSString *document = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0];
return [document stringByAppendingPathComponent:@"xcode6.dmg"];
}
- (void)setProgress:(float)newProgress {
_progressVIew.progress = newProgress;
_label.text = [NSString stringWithFormat:@"%.2f%%", newProgress * 100];
}
// ASI 非 ARC,系統不會自動釋放,必須手動收尾
- (void)dealloc {
[_request clearDelegatesAndCancel];
}
暫存檔機制的意義在於:下載途中隨時可能失敗,若直接寫入最終檔案,中斷後就得從零開始。有了暫存檔,配合 setAllowResumeForFileDownloads:YES,ASI 會自動帶上 Range 標頭向伺服器請求剩餘部分——前提是伺服器必須支援 Range 請求,否則續傳會靜默失效,變成每次重新下載。
另外,clearDelegatesAndCancel 一定要在 dealloc 或取消流程中呼叫。非 ARC 環境下若漏掉這一步,請求回來時 delegate 可能已被釋放,直接造成 crash。