iOS邊練邊學--NSURLSessionDataTask實現檔案真正的斷點續傳

來源:互聯網
上載者:User

標籤:

實現重點:

  • NSURLSessionDataTask要佈建要求頭,從路徑中擷取檔案已經下載的長度(檔案沒有下載過的話,長度為0)。通過這個長度佈建要求的Range

  • 接收到請求的時候key:檔案名稱(經過MD5加密過的URL,Url保證了檔案名稱的唯一) Value:該檔案已經下載過的長度。儲存成plist檔案,方便對下載檔案的判斷
  • 利用NSOutUpStream寫檔案
  • 在任務完成的代理方法裡面,NSOutUpStream關閉並且清空,對應的task清空,對應的session清空

代碼如下:

  1 #import "ViewController.h"  2 #import "NSString+Hash.h"  3   4 // 下載檔案的URL  5 #define ChaosFileURL @"http://120.25.226.186:32812/resources/videos/minion_01.mp4"  6   7 // 根據檔案唯一的URL MD5值 作為檔案名稱  8 #define ChaosFileName ChaosFileURL.md5String  9  10 // 用來隱藏檔總長度的plist檔案 key:檔案名稱的MD5值 value:檔案總長度 11 #define ChaosDownloadFilesPlist [[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:@"downloadFiles.plist"] 12  13 // 下載檔案的全路徑 14 #define ChaosFileFullPath [[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:ChaosFileName] 15  16 // 已經下載的檔案長度 17 #define ChaosDownloadLength [[[NSFileManager defaultManager] attributesOfItemAtPath:ChaosFileFullPath error:nil][@"NSFileSize"] integerValue] 18  19 @interface ViewController () <NSURLSessionDataDelegate> 20  21 /** stream */ 22 @property(nonatomic,strong) NSOutputStream *stream; 23  24 /** session */ 25 @property(nonatomic,strong) NSURLSession *session; 26  27 /** task */ 28 @property(nonatomic,strong) NSURLSessionDataTask *task; 29  30 /** totalLength */ 31 @property(nonatomic,assign) NSInteger totalLength; 32  33 /** downloadLength */ 34 @property(nonatomic,assign) NSInteger downloadLength; 35  36 @end 37  38 @implementation ViewController 39  40 - (NSURLSession *)session 41 { 42     if (_session == nil) { 43          44         _session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration] delegate:self delegateQueue:[[NSOperationQueue alloc] init]]; 45     } 46      47     return _session; 48 } 49  50 - (NSURLSessionDataTask *)task 51 { 52     if (_task == nil) { 53          54         // 獲得檔案總長度 55         NSInteger totalLength = [[NSDictionary dictionaryWithContentsOfFile:ChaosDownloadFilesPlist][ChaosFileName] integerValue]; 56         // 請求同一個檔案,判斷下載檔案長度;如果沒下載過此檔案,totalLength = 0 57         if (totalLength && ChaosDownloadLength == totalLength) { 58             NSLog(@"檔案已經下載過."); 59             return nil; 60         } 61          62         NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:ChaosFileURL]]; 63          64         // 佈建要求頭 -- range 這次從哪裡開始請求資料 格式:bytes=***-***(從指定開始到指定結束)  或者:bytes=***-(從指定位置到結束) 65         NSString *range = [NSString stringWithFormat:@"bytes=%zd-",ChaosDownloadLength]; 66          67         [request setValue:range forHTTPHeaderField:@"Range"]; 68          69         _task = [self.session dataTaskWithRequest:request]; 70          71     } 72     return _task; 73 } 74  75 // 開始 76 - (IBAction)startClick:(id)sender { 77      78     [self.task resume]; 79 } 80 // 暫停 81 - (IBAction)pauseClick:(id)sender { 82      83     [self.task suspend]; 84 } 85  86 - (void)viewDidLoad { 87     [super viewDidLoad]; 88 } 89  90 #pragma mark - <NSURLSessionDataDelegate> 91 /**  92  * 接收到響應的時候調用 93  */ 94 - (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveResponse:(NSHTTPURLResponse *)response completionHandler:(void (^)(NSURLSessionResponseDisposition))completionHandler 95 { 96     // 調用blcok,才能接受到資料 97     completionHandler(NSURLSessionResponseAllow); 98     // 初始化stream 99     self.stream = [NSOutputStream outputStreamToFileAtPath:ChaosFileFullPath append:YES];100     [self.stream open];101     102     // 擷取檔案總長度103     self.totalLength = [response.allHeaderFields[@"Content-Length"] integerValue] + ChaosDownloadLength;104     105     // 接收到伺服器響應的時候隱藏檔的總長度到plist,實現多檔案下載,先取出字典,給字典賦值最後寫入。106     // 錯誤做法:直接寫入檔案,會用這次寫入的資訊覆蓋原來所有的資訊107     NSMutableDictionary *dict = [NSMutableDictionary dictionaryWithContentsOfFile:ChaosDownloadFilesPlist];108     // 字典可能為空白109     if (dict == nil) dict = [NSMutableDictionary dictionary];110     // 寫入檔案111     dict[ChaosFileName] = @(self.totalLength);112     [dict writeToFile:ChaosDownloadFilesPlist atomically:YES];113 }114 115 /**116  * 接收到伺服器發來的資料的時候調用 -- 有可能調用多次117  */118 - (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveData:(NSData *)data119 {120     // 寫入資料121     [self.stream write:[data bytes] maxLength:data.length];122     // 擷取已經下載的長度123     self.downloadLength = ChaosDownloadLength;124     // 計算進度125     NSLog(@"%f",1.0 * self.downloadLength / self.totalLength);126 }127 128 /**129  * 任務完成的時候調用130  */131 - (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error132 {133     NSLog(@"----finish");134     [self.stream close];135     self.stream = nil;136     137     // 一個任務對應一個檔案,用完清空138     self.task = nil;139 }140 @end

 

iOS邊練邊學--NSURLSessionDataTask實現檔案真正的斷點續傳

聯繫我們

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