通过查看AFNetworking源码可以知道是通过NSURLSession来实现的,所以还是要理解NSURLSession。
NSURLSessionTask 包括 NSURLSessionDataTask 与 NSURLSessionDownloadTask。
NSURLSessionDataTask:可以处理常用的GET,POST请求。
NSURLSessionDownloadTask:用于处理下载请求。
NSURLSession * session = [NSURLSession sharedSession];
NSURLSessionDataTask * task = [session dataTaskWithURL:[NSURL URLWithString:urlStr] completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
NSString * str = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
}];
[task resume];
NSMutableURLRequest * request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:urlStr]];
request.HTTPMethod = @"POST";
request.HTTPBody = [@"appID=1" dataUsingEncoding:NSUTF8StringEncoding];
NSURLSession * session = [NSURLSession sharedSession];
NSURLSessionDataTask * postTask = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
}];
[postTask resume];
NSURLSessionDataTask * downloadTask = [session dataTaskWithURL:[NSURL URLWithString:urlStr] completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
UIImage * image = [UIImage imageWithData:data];
}];
[downloadTask resume];
NSURLSessionDownloadTask * downloadTask = [session downloadTaskWithURL:[NSURL URLWithString:urlStr] completionHandler:^(NSURL * _Nullable location, NSURLResponse * _Nullable response, NSError * _Nullable error) {
// 会下载到一个临时文件.tmp,所以需要我们把文件移动到cache文件中重新保存
// 目标文件路径
NSString *path = [[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:response.suggestedFilename];
// 移动到目标路径
[[NSFileManager defaultManager] moveItemAtURL:location toURL:[NSURL fileURLWithPath:path] error:nil];
UIImage * image = [UIImage imageWithContentsOfFile:path];
}];
[downloadTask resume];
此处需要注意:需要把临时文件.tmp 移动到cache文件中保存。
其中 response.suggestedFilename 为推荐的文件名,用于将.tmp文件转换为可使用的文件,用代理实现时可以通过 downloadTask.response.suggestedFilename 获取对应的推荐名。
NSURLSessionDataTask:最原始的请求方式,所以大部分的请求都能用他完成,不过好多逻辑需要我们自己处理。
NSURLSessionDownloadTask:专门用于下载请求,对内存消耗有很好的处理,并且实时将下载内容存入沙河临时文件。
[postTask cancel]; 直接取消请求,进入请求失败方法;如果请求已发送成功,则取消失败。
[session finishTasksAndInvalidate]; 等请求完成以后取消请求。
[session invalidateAndCancel]; 直接取消请求
后续添加 断点下载
如果下载时下载不成功,遇到since it does not conform to ATS policy问题,则需要在plist中添加以下代码: