從0.94版本開始,ASIHTTPRequest可以恢復中斷的下載
- (IBAction)resumeInterruptedDownload:(id)sender
{
NSURL *url = [NSURL URLWithString:
@"http://www.dreamingwish.com/wp-content/uploads/2011/10/asihttprequest-auth.png"];
ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
NSString *downloadPath = @"/Users/ben/Desktop/asi.png";
//當request完成時,整個文件會被移動到這裏
[request setDownloadDestinationPath:downloadPath];
//這個文件已經被下載了一部分
[request setTemporaryFileDownloadPath:@"/Users/ben/Desktop/asi.png.download"];
[request setAllowResumeForFileDownloads:YES];
[request startSynchronous];
//整個文件將會在這裏
NSString *theContent = [NSString stringWithContentsOfFile:downloadPath];
}
這個特性只對下載數據到文件中有效,你必須爲一下情況的request設置allowResumeForFileDownloads 爲YES:
- 任何你希望將來可以斷點續傳的下載(否則,ASIHTTPRequest會在取消或者釋放內存時將臨時文件刪除)
- 任何你要進行斷點續傳的下載
另外,你必須自己設置一個臨時下載路徑(setTemporaryFileDownloadPath),這個路徑是未完成的數據的路徑。新的數據將會被添加到這個文件,當下載完成時,這個文件將被移動到downloadDestinationPath 。
斷點續傳的工作原理是讀取temporaryFileDownloadPath的文件的大小,並使用Range: bytes=x HTTP頭來請求剩餘的文件內容。
ASIHTTPRequest並不檢測是否存在Accept-Ranges頭(因爲額外的HEAD頭請求會消耗額外的資源),所以只有確定服務器支持斷點續傳下載時,再使用這個特性。