一、NSURLSession的基本概念
1.三种工作模式
默认会话模式(default):工作模式类似于原来的NSURLConnection,使用的是基于磁盘缓存的持久化策略,使用用户keychain中保存的证书进行认证授权。
瞬时会话模式(ephemeral):该模式不使用磁盘保存任何数据。所有和会话相关的caches,证书,cookies等都被保存在RAM中,因此当程序使会话无效,这些缓存的数据就会被自动清空。
后台会话模式(background):该模式在后台完成上传和下载,在创建Configuration对象的时候需要提供一个NSString类型的ID用于标识完成工作的后台会话。
二、NSURLSession的用法
1.NSURLSession中的类:
//使用静态的sharedSession的方法,该类使用共享的会话,该回话使用全局的Cache,Cookie和证书
+ (NSURLSession *)sharedSession;
//根据NSURLSessionConfiguration创建对应配置的会话
+ (NSURLSession *)sessionWithConfiguration:(NSURLSessionConfiguration *)configuration;
//也是根据NSURLSessionConfiguration创建对应配置的会话,并且可以指定seesion的委托和委托所处的队列
+ (NSURLSession *)sessionWithConfiguration:(NSURLSessionConfiguration *)configuration delegate:(id <NSURLSessionDelegate>)delegate delegateQueue:(NSOperationQueue *)queue;
2.NSURLSessionConfiguration类
+ (NSURLSessionConfiguration *)defaultSessionConfiguration; //默认
+ (NSURLSessionConfiguration *)ephemeralSessionConfiguration; //瞬时
+ (NSURLSessionConfiguration *)backgroundSessionConfiguration:(NSString *)identifier; //后台
3.NSURLSessionTask类
NSURLSessionTask是一个抽象类,它有三个子类NSURLSessionDataTask,NSURLSessionUploadTask和NSURLSessionDownloadTask。这三个类封装了现代应用程序的三个基本网络任务:获取数据,比如JSON或XML,以及上传和下载文件。
下面是其继承关系:
三、三种Task的用法
1.NSURLSessionDataTask
//根据url创建请求
NSURL *url = [NSURL URLWithString:@""];
NSURLSession *session = [NSURLSession sharedSession];
NSURLSessionDataTask *dataTask = [session dataTaskWithURL:url completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
}];
// 使用resume方法启动任务
[dataTask resume];
//根据request创建请求
NSURL *url = [NSURL URLWithString:@""];
NSURLSession *session = [NSURLSession sharedSession];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
//可以设置header
[request setValue:@"" forHTTPHeaderField:@""];
NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
}];
// 使用resume方法启动任务
[dataTask resume];
2.NSURLSessionUploadTask
NSData *data = [NSData dataWithContentsOfFile:@""];//需要上传的数据
NSURL *url = [NSURL URLWithString:@""];
NSURLSession *session = [NSURLSession sharedSession];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
NSURLSessionUploadTask *dataTask = [session uploadTaskWithRequest:request fromData:data completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
}];
[dataTask resume];
3.NSURLSessionDownloadTask
3.1 简单的下载任务
//使用downloadTaskWithURL:completionHandler:进行小文件下载,例如图片
NSURL *url = [NSURL URLWithString:@""];
NSURLSession *session = [NSURLSession sharedSession];
NSURLSessionDownloadTask *dataTask = [session downloadTaskWithURL:url completionHandler:^(NSURL * _Nullable location, NSURLResponse * _Nullable response, NSError * _Nullable error) {
//location为文件下载完成之后存放的位置,我们需要把移动到想要存放的路径下;
//移动到Documents文件夹下
NSString *documentsPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject];
NSURL *documentsDirectoryURL = [NSURL fileURLWithPath:documentsPath];
NSURL *fileURL = [documentsDirectoryURL URLByAppendingPathComponent:[[response URL] lastPathComponent]];
NSFileManager *fileManager = [NSFileManager defaultManager];
if ([fileManager fileExistsAtPath:[fileURL path] isDirectory:NULL]) {
[fileManager removeItemAtURL:fileURL error:NULL];
}
[fileManager moveItemAtURL:location toURL:fileURL error:NULL];
}];
[dataTask resume];
3.2 断点续传
@interface ViewController ()<NSURLSessionDownloadDelegate>
@property (nonatomic,strong) NSURLSession *session;
@property (nonatomic,strong) NSURLSessionDownloadTask *downLoadTask;
@property (nonatomic,strong) NSData *resumeData;
@property (nonatomic,strong) UIButton *downLoadBtn;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
UIButton *downLoadBtn = [UIButton buttonWithType:UIButtonTypeCustom];
downLoadBtn.frame = CGRectMake(20, 100, 100, 40);
[downLoadBtn setTitle:@"下载" forState:UIControlStateNormal];
[downLoadBtn setTitle:@"暂停" forState:UIControlStateSelected];
[downLoadBtn addTarget:self action:@selector(downLoad) forControlEvents:UIControlEventTouchUpInside];
self.downLoadBtn = downLoadBtn;
}
-(void)createSession{
NSURLSessionConfiguration *defaultConfig = [NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession *session = [NSURLSession sessionWithConfiguration:defaultConfig delegate:self delegateQueue:nil];
self.session = session;
}
#pragma mark -- 下载/暂停
-(void)downLoad{
if (!self.downLoadTask) {
NSURL *url = [NSURL URLWithString:@"https://httpbin.org/image/png"];//下载地址
if (!self.session) {
[self createSession];
}
if (self.resumeData) {
self.downLoadTask = [self.session downloadTaskWithResumeData:self.resumeData];
}else{
self.downLoadTask = [self.session downloadTaskWithURL:url];
}
[self.downLoadTask resume];
self.downLoadBtn.selected = YES;
}else{
[self.downLoadTask cancelByProducingResumeData:^(NSData * _Nullable resumeData) {
self.resumeData = resumeData;
self.downLoadTask = nil;
self.downLoadBtn.selected = NO;
}];
}
}
#pragma mark -- NSURLSessionDownloadDelegate 代理方法
- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask
didFinishDownloadingToURL:(NSURL *)location{
//location为下载文件的位置
self.downLoadBtn.selected = NO;
self.downLoadBtn.enabled = NO;
NSString *documentsPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject];
NSURL *documentsDirectoryURL = [NSURL fileURLWithPath:documentsPath];
NSURL *fileURL = [documentsDirectoryURL URLByAppendingPathComponent:@"zz.png"];
NSFileManager *fileManager = [NSFileManager defaultManager];
if ([fileManager fileExistsAtPath:[fileURL path] isDirectory:NULL]) {
[fileManager removeItemAtURL:fileURL error:NULL];
}
[fileManager moveItemAtURL:location toURL:fileURL error:NULL];
NSLog(@"%@",fileURL);
}
//想要查看下载进度可以实现下面这个代理方法
- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask
didWriteData:(int64_t)bytesWritten
totalBytesWritten:(int64_t)totalBytesWritten
totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite{
}
//在恢复下载时,下面这个代理方法将被调用:
- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask
didResumeAtOffset:(int64_t)fileOffset
expectedTotalBytes:(int64_t)expectedTotalBytes{
}
@end
断点续传也可以使用NSURLSessionDataTask,可以设置请求头中得"Rang".
// 创建请求
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url]];
// 设置请求头
NSString *range = [NSString stringWithFormat:@"bytes=%zd-", ZXDDownloadLength(url)];
[request setValue:range forHTTPHeaderField:@"Range"];
// 创建一个Data任务
NSURLSessionDataTask *task = [session dataTaskWithRequest:request];
网友评论