iOS開發ASIHTTPRequest斷點續傳(下載)

來源:互聯網
上載者:User

本文為大家介紹了iOS開發ASIHTTPRequest斷點續傳(下載)的內容,其中包括ASIHTTPRequest可以恢複中斷的下載,設定一個臨時下載路徑,斷點續傳的工作原理等等內容。

從0.94版本開始,ASIHTTPRequest可以恢複中斷的下載。

這個特性只對下載資料到檔案中有效,你必須為一下情況的request設定allowResumeForFileDownloads 為YES:

  • 任何你希望將來可以斷點續傳的下載否則,ASIHTTPRequest會在取消或者釋放記憶體時將臨時檔案刪除)
  • 任何你要進行斷點續傳的下載

另外,你必須自己設定一個臨時下載路徑setTemporaryFileDownloadPath),這個路徑是未完成的資料的路徑。新的資料將會被添加到這個檔案,當下載完成時,這個檔案將被移動到downloadDestinationPath 。

 
  1. - (IBAction)resumeInterruptedDownload:(id)sender 
  2.   NSURL *url = [NSURL URLWithString: 
  3.     @"http://www.dreamingwish.com/wp-content/uploads/2011/10/asihttprequest-auth.png"]; 
  4.   ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url]; 
  5.   
  6.   NSString *downloadPath = @"/Users/ben/Desktop/asi.png"; 
  7.   
  8.   //當request完成時,整個檔案會被移動到這裡 
  9.   [request setDownloadDestinationPath:downloadPath]; 
  10.   
  11.   //這個檔案已經被下載了一部分 
  12.   [request setTemporaryFileDownloadPath:@"/Users/ben/Desktop/asi.png.download"]; 
  13.   [request setAllowResumeForFileDownloads:YES]; 
  14.   [request startSynchronous]; 
  15.   
  16.   //整個檔案將會在這裡 
  17.   NSString *theContent = [NSString stringWithContentsOfFile:downloadPath]; 
  18. }

斷點續傳的工作原理是讀取temporaryFileDownloadPath的檔案的大小,並使用Range: bytes=x HTTP頭來請求剩餘的檔案內容。

ASIHTTPRequest並不檢測是否存在Accept-Ranges頭因為額外的HEAD頭請求會消耗額外的資源),所以只有確定伺服器支援斷點續傳下載時,再使用這個特性。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.