要想有下载进度就要用NSURLSessionDownloadTask的代理方法
//这个要创建NSURLSessionConfiguration对象
NSURLSessionConfiguration *scf = [NSURLSessionConfiguration defaultSessionConfiguration];
//创建session
NSURLSession *session = [NSURLSession sessionWithConfiguration:scf delegate:self delegateQueue:[NSOperationQueue mainQueue]];
//创建一个url
NSURL *url = [NSURL URLWithString:@"http://192.168.1.100:8080/TFServer/resources/videos/minion_01.mp4"];
//创建一个任务
NSURLSessionDownloadTask *task = [session downloadTaskWithURL:url];
//开始任务
[task resume];
实现代理方法
//下载完成调用
- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask
didFinishDownloadingToURL:(NSURL *)location {
// location : 临时文件的路径(下载好的文件)
NSString *caches = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
// response.suggestedFilename : 建议使用的文件名,一般跟服务器端的文件名一致
NSString *file = [caches stringByAppendingPathComponent:downloadTask.response.suggestedFilename];
// 将临时文件剪切或者复制Caches文件夹
NSFileManager *mgr = [NSFileManager defaultManager];
// AtPath : 剪切前的文件路径
// ToPath : 剪切后的文件路径
[mgr moveItemAtPath:location.path toPath:file error:nil];
}
//下载过程中调用
- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask
didWriteData:(int64_t)bytesWritten
totalBytesWritten:(int64_t)totalBytesWritten
totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite {
double process = (double)totalBytesWritten / totalBytesExpectedToWrite;
NSLog(@"-------%f", process);
}
//恢复下载调用
- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask
didResumeAtOffset:(int64_t)fileOffset
expectedTotalBytes:(int64_t)expectedTotalBytes {
}