block下载任务
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
//会话
NSURLSession *session=[NSURLSession sharedSession];
//2.根据会话创建任务
NSURLSessionDownloadTask *downloadTask= [session downloadTaskWithURL:[NSURL URLWithString:IMAGE_URL] completionHandler:^(NSURL * _Nullable location, NSURLResponse * _Nullable response, NSError * _Nullable error) {
//location是下载的本地地址
NSLog(@"location=%@",location);
UIImage *image=[UIImage imageWithData:[NSData dataWithContentsOfURL:location]];
dispatch_async(dispatch_get_main_queue(), ^{
self.imagview.image=image;
});
}];
//3.启动任务
[downloadTask resume];
}
下载代理方法
#import "ViewController.h"
#define MYURL @"http://vjs.zencdn.net/v/oceans.mp4"
@interface ViewController ()<NSURLSessionDownloadDelegate>
@property (nonatomic,strong)NSURLSessionDownloadTask *task;
@property(nonatomic,strong) NSData *data;
@property(nonatomic,strong) NSURLSession *session;
@end
@implementation ViewController
//创建会话
-(NSURLSession *)session{
if(!_session){
_session=[NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration] delegate:self delegateQueue:[[NSOperationQueue alloc]init]];
}
return _session;
}
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
}
- (IBAction)start:(UIButton *)sender {
//根据会话创建下载任务
self.task=[self.session downloadTaskWithURL:[NSURL URLWithString:MYURL]];
//启动任务
[self.task resume];
}
- (IBAction)pause:(UIButton *)sender {
// [self.task suspend];//可以恢复任务
//cancelByProducingResumeData任务无法恢复,如果还是想能恢复继续下载,则记录下当前下载的数据
[self.task cancelByProducingResumeData:^(NSData * _Nullable resumeData) {
//resumeData表示当前下载了多少数据
self.data=resumeData;
}];
}
- (IBAction)resume:(UIButton *)sender {
// [self.task resume];
//对应cancelByProducingResumeData的在暂停的基础上继续下载
self.task=[self.session downloadTaskWithResumeData:self.data];
[self.task resume];
}
#pragma mark -协议方法
-(void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error{
}
//下载进度
/*
bytesWritten 当前次下载的数据大小
totalBytesWritten 总共下载了多少数据
totalBytesExceptedToWrite
*/
-(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 didResumeAtOffset:(int64_t)fileOffset expectedTotalBytes:(int64_t)expectedTotalBytes{
}
//下载之后 文件所在位置
-(void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didFinishDownloadingToURL:(NSURL *)location{
//location文件下载的路径
}
@end