NSURLSession *session = [NSURLSession sharedSession];
// 可以不用像connection一样用代理监听, 直接会下载文件, 但是无法获得下载的进度
NSURLSessionDownloadTask *task = [session
downloadTaskWithURL:[NSURL URLWithString:@""]
completionHandler:^(NSURL * _Nullable location, NSURLResponse * _Nullable response, NSError * _Nullable error) {
// 文件存储的真实路径
NSString *file = [[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:response.suggestedFilename];
// 剪切location的临时文件到真实路径
NSFileManager *mgr = [NSFileManager defaultManager];
[mgr moveItemAtURL:location toURL:[NSURL fileURLWithPath:file] error:nil];
}];
[task resume];
///////////////////////////////////////////////////////////////////////////////////////////////////////////
// 遵搜三种协议 ,但是 最基本的哪一个 协议的继承性
@interface ViewController ()<NSURLSessionDataDelegate>// 继承子类就相当于继承了父类协议
@end
//协议间的继承关系: <NSURLSessionDataDelegate>:<NSURLSessionTaskDelegate>:<NSURLSessionDelegate>
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// NSURLSession *session = [NSURLSession sharedSession];
// session.delegate = self; // 不能直接设置delegate是 readonly
// 只能一开始的时候创建其代理
NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration] delegate:self delegateQueue:[[NSOperationQueue alloc] init]];
// 父协议,但是可以传入子协议:nullable id <NSURLSessionDelegate>
NSURLSessionDownloadTask *task = [session downloadTaskWithRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@""]] completionHandler:^(NSURL * _Nullable location, NSURLResponse * _Nullable response, NSError * _Nullable error) {}];
[task resume];
}
// 代理方法
-(void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveResponse:(NSURLResponse *)response completionHandler:(void (^)(NSURLSessionResponseDisposition))completionHandler{
// 要启动,否则无法下载
completionHandler(NSURLSessionResponseAllow);// 允许 后再继续请求数
}
-(void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveData:(NSData *)data{
}
-(void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error{
}