NSURLSession
之前发送网络请求的过程URL-URLRequest-URLConnection , NSURLSession 面向任务,更加高级
NSURLSession- iOS7.0 以后 用于替代 NSURLConnection 支持后台运行的网络任务 暂停、停止、重启网络任务,不再需要自己封装 NSOperation 下载、断点续传、异步下载 上传、异步上传 获取下載、上传的进度NSURLSession 可以发起以下任务,默认所有的任务都是挂起的:DataTask UploadTask DownloadTask NSURLSessionConfigration :配置请求的信息
DataTask
[NSURLSession sharedSession] 默认返回一个单例对象,默认发送get请求
NSURL *url = [NSURL URLWithString:@""];
NSURLSession *session = [NSURLSession sharedSession];
NSURLSessionDataTask *dataTask = [session dataTaskWithURL:url completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
id json = [NSJSONSerialization JSONObjectWithData:data options:0 error:NULL];
NSLog(@"hello");
}];
[dataTask resume];
NSURL *url = [NSURL URLWithString:@""];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
NSString *body = @"username=123&password=123";
request.HTTPMethod = @"post";
request.HTTPBody = [body dataUsingEncoding:NSUTF8StringEncoding];
NSURLSession *session = [NSURLSession sharedSession];
NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
id json = [NSJSONSerialization JSONObjectWithData:data options:0 error:NULL];
NSLog(@"hello");
}];
[dataTask resume];
DownloadTask
下载DownloadTask 默认把文件下载到沙盒的tmp 文件夹,下载完成后不会文件做任何操作,会自动删除文件,下载过程是异步的
NSURL *url = [NSURL URLWithString:@""];
[[[NSURLSession sharedSession]downloadTaskWithURL:url completionHandler:^(NSURL * _Nullable location, NSURLResponse * _Nullable response, NSError * _Nullable error) {
NSString *doc = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
[[NSFileManager defaultManager] copyItemAtPath:location.path toPath:doc error:NULL];
}]resume];
#import "ViewController.h"
@interface ViewController () <NSURLSessionDownloadDelegate>
@property(nonatomic,strong)NSURLSession *session;
@property(nonatomic,strong)NSURLSessionDownloadTask *downloadTask;
@property(nonatomic,strong)NSData *resumeData;
@end
@implementation ViewController
#pragma mark - 懒加载
-(NSURLSession *)session{
if (_session ==nil) {
NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration];
_session = [NSURLSession sessionWithConfiguration:config delegate:self delegateQueue:[NSOperationQueue new]];
}
return _session;
}
#pragma mark - NSURLSessionDownloadDelegate
-(void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didFinishDownloadingToURL:(NSURL *)location{
NSLog(@"下载完成:%@",location);
}
- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didResumeAtOffset:(int64_t)fileOffset expectedTotalBytes:(int64_t)expectedTotalBytes{
NSLog(@"断点续传");
}
- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didWriteData:(int64_t)bytesWritten totalBytesWritten:(int64_t)totalBytesWritten totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite{
float process = totalBytesWritten*1.0/totalBytesExpectedToWrite;
NSLog(@"下载进度:%f",process);
}
#pragma mark - 下载
-(void)download{
NSURL *url = [NSURL URLWithString:@""];
NSURLSessionDownloadTask *downloadTask = [self.session downloadTaskWithURL:url];
self.downloadTask = downloadTask;
[downloadTask resume];
}
-(void)pause{
[self.downloadTask cancelByProducingResumeData:^(NSData * _Nullable resumeData) {
self.resumeData = resumeData;
NSString *path = [NSTemporaryDirectory() stringByAppendingPathComponent:@"test.tmp"];
[self.resumeData writeToFile:path atomically:YES];
self.downloadTask = nil;
}];
}
-(void)resume{
NSString *path = [NSTemporaryDirectory() stringByAppendingPathComponent:@"test.tmp"];
NSFileManager *fileManager = [NSFileManager defaultManager];
if([fileManager fileExistsAtPath:path]){
self.resumeData = [NSData dataWithContentsOfFile:path];
}
if(self.resumeData == nil){return;}
self.downloadTask = [self.session downloadTaskWithResumeData:self.resumeData];
[self.downloadTask resume];
self.resumeData = nil;
}
#pragma mark - 主函数
- (void)viewDidLoad {
[super viewDidLoad];
}
@end
- 创建
session 的时候,队列设置为nil ,和写[[NSOperationQueue alloc]init] 的效果是一样的
_session = [NSURLSession sessionWithConfiguration:config delegate:self delegateQueue:nil];
|