使用NSURLSessionDownloadTask實現大檔案下載-監聽下載進度

來源:互聯網
上載者:User

標籤:defaults   config   複雜   點擊   mil   寫入   ring   eof   nconf   

(1)建立NSURLSession並設定代理,通過NSURLSessionDownloadTask並以代理的方式來完成大檔案的下載

     //1.建立NSULRSession,設定代理    self.session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration] delegate:self delegateQueue:[NSOperationQueue mainQueue]];    //2.建立task    NSURL *url = [NSURL URLWithString:@"http://120.25.226.186:32812/resources/videos/minion_01.mp4"];    self.downloadTask = [self.session downloadTaskWithURL:url];    //3.執行task    [self.downloadTask resume];

(2)常用代理方法的說明

    /* 1.當接收到下載資料的時候調用,可以在該方法中監聽檔案下載的進度 該方法會被調用多次 totalBytesWritten:已經寫入到檔案中的資料大小 totalBytesExpectedToWrite:目前檔案的總大小 bytesWritten:本次下載的檔案資料大小 */-(void)URLSession:(nonnull NSURLSession *)session downloadTask:(nonnull NSURLSessionDownloadTask *)downloadTask didWriteData:(int64_t)bytesWritten totalBytesWritten:(int64_t)totalBytesWritten totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite/* 2.恢複下載的時候調用該方法 fileOffset:恢複之後,要從檔案的什麼地方開發下載 expectedTotalBytes:該檔案資料的總大小 */-(void)URLSession:(nonnull NSURLSession *)session downloadTask:(nonnull NSURLSessionDownloadTask *)downloadTask didResumeAtOffset:(int64_t)fileOffset expectedTotalBytes:(int64_t)expectedTotalBytes/* 3.下載完成之後調用該方法 */-(void)URLSession:(nonnull NSURLSession *)session downloadTask:(nonnull NSURLSessionDownloadTask *)downloadTask didFinishDownloadingToURL:(nonnull NSURL *)location/* 4.請求完成之後調用 如果請求失敗,那麼error有值 */-(void)URLSession:(nonnull NSURLSession *)session task:(nonnull NSURLSessionTask *)task didCompleteWithError:(nullable NSError *)error

(3)實現斷點下載相關代碼

    //如果任務,取消了那麼以後就不能恢複了    //    [self.downloadTask cancel];    //如果採取這種方式來取消任務,那麼該方法會通過resumeData儲存當前檔案的下載資訊    //只要有了這份資訊,以後就可以通過這些資訊來恢複下載    [self.downloadTask cancelByProducingResumeData:^(NSData * __nullable resumeData) {        self.resumeData = resumeData;    }];    -----------    //繼續下載    //首先通過之前儲存的resumeData資訊,建立一個下載任務    self.downloadTask = [self.session downloadTaskWithResumeData:self.resumeData];     [self.downloadTask resume];

(4)計算當前下載進度

    //擷取檔案下載進度    self.progress.progress = 1.0 * totalBytesWritten/totalBytesExpectedToWrite;

(5)局限性

01 如果使用者點擊暫停之後退出程式,那麼需要把恢複下載的資料寫一份到沙箱,代碼複雜度更02 如果使用者在下載中途未儲存恢複下載資料即退出程式,則不具備可操作性

使用NSURLSessionDownloadTask實現大檔案下載-監聽下載進度

相關文章

聯繫我們

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