#import "ViewController.h"
@interface ViewController () <NSURLSessionDownloadDelegate>
@end
@implementation ViewController
- (void)download{
// 获得NSURLSession对象
NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]
delegate:self
delegateQueue:[[NSOperationQueue alloc] init]];
// 获得下载任务
NSString *urlString = @"http://www.example.com:8080/resources/videos/minion_01.mp4";
NSURL *url = [NSURL URLWithString:urlString];
NSURLSessionDownloadTask *task = [session downloadTaskWithURL:url];
// 启动任务
[task resume];
}
#pragma mark - <NSURLSessionDownloadDelegate>
- (void)URLSession:(NSURLSession *)session
downloadTask:(NSURLSessionDownloadTask *)downloadTask
didResumeAtOffset:(int64_t)fileOffset
expectedTotalBytes:(int64_t)expectedTotalBytes{
NSLog(@"%s",__func__);
}
/**
* 每当写入数据到临时文件时,就会调用一次这个方法
* totalBytesExpectedToWrite:总大小
* totalBytesWritten: 已经写入的大小
* bytesWritten: 这次写入多少
*/
- (void)URLSession:(NSURLSession *)session
downloadTask:(NSURLSessionDownloadTask *)downloadTask
didWriteData:(int64_t)bytesWritten
totalBytesWritten:(int64_t)totalBytesWritten
totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite{
NSLog(@"%f", 1.0 * totalBytesWritten / totalBytesExpectedToWrite);
}
/**
*
* 下载完毕就会调用一次这个方法
*/
- (void)URLSession:(NSURLSession *)session
downloadTask:(NSURLSessionDownloadTask *)downloadTask
didFinishDownloadingToURL:(NSURL *)location{
// 文件将来存放的真实路径
NSString *file = [[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:downloadTask.response.suggestedFilename];
NSLog(@"%@",file);
// 剪切location的临时文件到真实路径
NSFileManager *mgr = [NSFileManager defaultManager];
[mgr moveItemAtURL:location toURL:[NSURL fileURLWithPath:file] error:nil];
}
- (void)URLSession:(NSURLSession *)session
task:(NSURLSessionTask *)task
didCompleteWithError:(NSError *)error{
NSLog(@"%s",__func__);
}
// 0.000604
// 0.001548
// 0.002808
// 0.003280
// 0.999315
// 0.999787
// 1.000000
// /Users/zhaoyingxin/Library/Developer/CoreSimulator/Devices/1146129D-06F4-457B-83AC-B97F3B7ECA32/data/Containers/Data/Application/30163B0A-635F-4D01-811D-74968D3C7333/Library/Caches/minion_01.mp4
// -[ViewController URLSession:task:didCompleteWithError:]
@end
网友评论