AFNetworking實現程式重新啟動時的斷點續傳

來源:互聯網
上載者:User

標籤:

 

用AFNetworking實現斷點續傳的功能,研究後,發現AFNetworking雖然支援下載檔案的暫停和繼續, 但是程式重新啟動後再次下載無法進行續傳。網上有說可以通過AFDownloadRequestOperation這個AFNetworking的擴充庫 來實現重新啟動後的續傳,但是經過本人測試,這個庫在最新的AFNetworking上會報錯,無奈之下,參考他的代碼,自己實現了一個,在這裡分享給大 家。

實現的代碼如下:

    //擷取已下載的檔案大小      - (unsigned long long)fileSizeForPath:(NSString *)path {          signed long long fileSize = 0;          NSFileManager *fileManager = [NSFileManager new]; // default is not thread safe          if ([fileManager fileExistsAtPath:path]) {              NSError *error = nil;              NSDictionary *fileDict = [fileManager attributesOfItemAtPath:path error:&error];              if (!error && fileDict) {                  fileSize = [fileDict fileSize];              }          }          return fileSize;      }      //開始下載      - (void)startDownload {          NSString *downloadUrl = @"http://www.xxx.com/xxx.zip";          NSString *cacheDirectory = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) objectAtIndex:0];          NSString *downloadPath = [cacheDirectory stringByAppendingPathComponent:@"xxx.zip"];          NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:downloadUrl]];          //檢查檔案是否已經下載了一部分          unsigned long long downloadedBytes = 0;          if ([[NSFileManager defaultManager] fileExistsAtPath:downloadPath]) {          //擷取已下載的檔案長度              downloadedBytes = [self fileSizeForPath:downloadPath];              if (downloadedBytes > 0) {                  NSMutableURLRequest *mutableURLRequest = [request mutableCopy];                  NSString *requestRange = [NSString stringWithFormat:@"bytes=%llu-", downloadedBytes];                  [mutableURLRequest setValue:requestRange forHTTPHeaderField:@"Range"];                  request = mutableURLRequest;              }          }          //不使用緩衝,避免斷點續傳出現問題          [[NSURLCache sharedURLCache] removeCachedResponseForRequest:request];          //下載請求          AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];          //下載路徑          operation.outputStream = [NSOutputStream outputStreamToFileAtPath:downloadPath append:YES];          //下載進度回調          [operation setDownloadProgressBlock:^(NSUInteger bytesRead, long long totalBytesRead, long long totalBytesExpectedToRead) {              //下載進度              float progress = ((float)totalBytesRead + downloadedBytes) / (totalBytesExpectedToRead + downloadedBytes);          }];          //成功和失敗回調          [operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {                            } failure:^(AFHTTPRequestOperation *operation, NSError *error) {                            }];          [operation start];      }  

 

需要注意的是,此種寫法僅適用於下載zip包,因為下載其他格式的檔案有可能出現資料過多的情況。當檔案已經下載完成時,再次調用該函數,無法判斷檔案是否已經下載完整,於是會再次下載,此時伺服器會報416錯,同時返回也會輸出到檔案中,使得檔案大小異常。但是zip格式不受影響。

轉載自 http://blog.csdn.net/zhaoxy_thu/article/details/21383515

 

AFNetworking實現程式重新啟動時的斷點續傳

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.