通過設置代理我們可以拿到下載進度,對于大文件,我們還需要做到開始、暫停、繼續以及取消等相應操作,這篇文章先簡單的介紹一下通過代理來實現文件下載的問題:
#import "ViewController.h"@interface ViewController ()<NSURLSessionDownloadDelegate>@end@implementation ViewController-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{ [self delegate];}-(void)delegate{ //1.url NSURL *url = [NSURL URLWithString:@"http://120.25.226.186:32812/resources/images/minion_03.png"]; //2.創建請求對象 NSURLRequest *request = [NSURLRequest requestWithURL:url]; //3.創建session :注意代理為NSURLSessionDownloadDelegate NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration] delegate:self delegateQueue:[NSOperationQueue mainQueue]]; //4.創建Task NSURLSessionDownloadTask *downloadTask = [session downloadTaskWithRequest:request]; //5.執行Task [downloadTask resume];}#pragma mark ----------------------#pragma mark NSURLSessionDownloadDelegate/** * 寫數據 * * @param session 會話對象 * @param downloadTask 下載任務 * @param bytesWritten 本次寫入的數據大小 * @param totalBytesWritten 下載的數據總大小 * @param totalBytesExpectedToWrite 文件的總大小 */-(void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didWriteData:(int64_t)bytesWritten totalBytesWritten:(int64_t)totalBytesWritten totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite{ //1. 獲得文件的下載進度 NSLog(@"%f",1.0 * totalBytesWritten/totalBytesExpectedToWrite);}/** * 當恢復下載的時候調用該方法 * * @param fileOffset 從什么地方下載 * @param expectedTotalBytes 文件的總大小 */-(void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didResumeAtOffset:(int64_t)fileOffset expectedTotalBytes:(int64_t)expectedTotalBytes{ NSLog(@"%s",__func__);}/** * 當下載完成的時候調用 * * @param location 文件的臨時存儲路徑 */-(void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didFinishDownloadingToURL:(NSURL *)location{ NSLog(@"%@",location); //1 拼接文件全路徑 NSString *fullPath = [[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:downloadTask.response.suggestedFilename]; //2 剪切文件 [[NSFileManager defaultManager]moveItemAtURL:location toURL:[NSURL fileURLWithPath:fullPath] error:nil]; NSLog(@"%@",fullPath);}/** * 請求結束 */-(void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error{ NSLog(@"didCompleteWithError");}@end
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持VEVB武林網。
新聞熱點
疑難解答