天天看點

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

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

實作的代碼如下:

​​

  1. //擷取已下載下傳的檔案大小  
  2. - (unsigned long long)fileSizeForPath:(NSString *)path {  
  3.     signed long long fileSize = 0;  
  4.     NSFileManager *fileManager = [NSFileManager new]; // default is not thread safe  
  5.     if ([fileManager fileExistsAtPath:path]) {  
  6.         NSError *error = nil;  
  7.         NSDictionary *fileDict = [fileManager attributesOfItemAtPath:path error:&error];  
  8.         if (!error && fileDict) {  
  9.             fileSize = [fileDict fileSize];  
  10.         }  
  11.     }  
  12.     return fileSize;  
  13. }  
  14. //開始下載下傳  
  15. - (void)startDownload {  
  16.     NSString *downloadUrl = @"http://www.xxx.com/xxx.zip";  
  17.     NSString *cacheDirectory = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) objectAtIndex:0];  
  18.     NSString *downloadPath = [cacheDirectory stringByAppendingPathComponent:@"xxx.zip"];  
  19.     NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:downloadUrl]];  
  20.     //檢查檔案是否已經下載下傳了一部分  
  21.     unsigned long long downloadedBytes = 0;  
  22.     if ([[NSFileManager defaultManager] fileExistsAtPath:downloadPath]) {  
  23.     //擷取已下載下傳的檔案長度  
  24.         downloadedBytes = [self fileSizeForPath:downloadPath];  
  25.         if (downloadedBytes > 0) {  
  26.             NSMutableURLRequest *mutableURLRequest = [request mutableCopy];  
  27.             NSString *requestRange = [NSString stringWithFormat:@"bytes=%llu-", downloadedBytes];  
  28.             [mutableURLRequest setValue:requestRange forHTTPHeaderField:@"Range"];  
  29.             request = mutableURLRequest;  
  30.     //不使用緩存,避免斷點續傳出現問題  
  31.     [[NSURLCache sharedURLCache] removeCachedResponseForRequest:request];  
  32.     //下載下傳請求  
  33.     AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];  
  34.     //下載下傳路徑  
  35.     operation.outputStream = [NSOutputStream outputStreamToFileAtPath:downloadPath append:YES];  
  36.     //下載下傳進度回調  
  37.     [operation setDownloadProgressBlock:^(NSUInteger bytesRead, long long totalBytesRead, long long totalBytesExpectedToRead) {  
  38.         //下載下傳進度  
  39.         float progress = ((float)totalBytesRead + downloadedBytes) / (totalBytesExpectedToRead + downloadedBytes);  
  40.     }];  
  41.     //成功和失敗回調  
  42.     [operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {  
  43.     } failure:^(AFHTTPRequestOperation *operation, NSError *error) {  
  44.     [operation start];  

繼續閱讀