本文為大家介紹了iOS開發ASIHTTPRequest斷點續傳(下載)的內容,其中包括ASIHTTPRequest可以恢複中斷的下載,設定一個臨時下載路徑,斷點續傳的工作原理等等內容。
從0.94版本開始,ASIHTTPRequest可以恢複中斷的下載。
這個特性只對下載資料到檔案中有效,你必須為一下情況的request設定allowResumeForFileDownloads 為YES:
- 任何你希望將來可以斷點續傳的下載否則,ASIHTTPRequest會在取消或者釋放記憶體時將臨時檔案刪除)
- 任何你要進行斷點續傳的下載
另外,你必須自己設定一個臨時下載路徑setTemporaryFileDownloadPath),這個路徑是未完成的資料的路徑。新的資料將會被添加到這個檔案,當下載完成時,這個檔案將被移動到downloadDestinationPath 。
- - (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];
- }
斷點續傳的工作原理是讀取temporaryFileDownloadPath的檔案的大小,並使用Range: bytes=x HTTP頭來請求剩餘的檔案內容。
ASIHTTPRequest並不檢測是否存在Accept-Ranges頭因為額外的HEAD頭請求會消耗額外的資源),所以只有確定伺服器支援斷點續傳下載時,再使用這個特性。