一. NSURLSession 是iOS7之后,针对下载,上传,提供的方案.
1.创建方法一:单例,不需要监听网络请求过程的网络会话才使用
NSURLSession *session =[NSURLSession sharedSession];
2.如果需要监听网络进度,需要自定义一个,并且需要设置代理并且需要一个全局的属性
NSURLSessionConfiguration *cgf = [];
NSURLSession *session = [NSURLSession sessionWithConfiguration:<#(nonnull NSURLSessionConfiguration *)#> delegate:<#(nullable id<NSURLSessionDelegate>)#> delegateQueue:<#(nullable NSOperationQueue *)#>]
NSURLSessionConfiguration用于配置会话的属性,可以通过该类配置会话的工作模式:
- + (NSURLSessionConfiguration *)defaultSessionConfiguration;
- + (NSURLSessionConfiguration *)ephemeralSessionConfiguration;
- + (NSURLSessionConfiguration *)backgroundSessionConfiguration:(NSString *)identifier;
在backgroundSessionConfiguration:方法中的identifier参数指定了会话的ID,用于标记后台的session。
二. 网络任务(task):在NSURLSession中有三种网络任务
1.用于普通非文件下载 get/post请求
NSURLSessionDataTask,实例化,对象有两种方式
1)实例化一个普通的网络任务
NSURLSessionDataTask *task = [session dataTaskWithRequest:<#(nonnull NSURLRequest *)#> completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) { }];
2)通过URL实例化一个对象
NSURLSessionDataTask *task = [session dataTaskWithURL:<#(nonnull NSURL *)#> completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
}];
2.用于网络文件下载的网络任务
NSURLSessionDownloadTask(不论文件大小)
1)通过一个request来实例化一个下载任务,一般用于小文件下载
NSURLSessionDownloadTask *task = [session downloadTaskWithRequest:<#(nonnull NSURLRequest *)#> completionHandler:^(NSURL * _Nullable location, NSURLResponse * _Nullable response, NSError * _Nullable error) {
}];
2)通过URL来实例化一个下载任务,一般用于小文件下载
NSURLSessionDownloadTask *task = [session downloadTaskWithURL:<#(nonnull NSURL *)#> completionHandler:^(NSURL * _Nullable location, NSURLResponse * _Nullable response, NSError * _Nullable error) {
}];
3)通过Resume实例化一个下载任务,用于断点下载
NSURLSessionDownloadTask *task = [session downloadTaskWithResumeData:<#(nonnull NSData *)#> completionHandler:^(NSURL * _Nullable location, NSURLResponse * _Nullable response, NSError * _Nullable error) {
}];
3.用于上传的网络任务,NSURLSessionUploadTask,目前只有一种方式,需要拼接数据
NSURLSessionUploadTask *task = [session uploadTaskWithRequest:<#(nonnull NSURLRequest *)#> fromData:<#(nullable NSData *)#> completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
}];
三.NSURLSession的使用分为三步
1)实例化一个对象 NSURLSession;
2)通过对象,实例化任务
3)开启任务 [task resume]
请求服务器数据(GET方式)
请求服务器数据分成异步和同步两种方式。
异步(非阻塞)
NSURL *url = [NSURL URLWithString :@"www.baidu.com"];
NSURLRequest *request = [NSURLRequest requestWithURL: url];
NSOperationQueue *queue = [[NSOperationQueue alloc] init];
[NSURLConnection sendAsynchronousRequest: request queue:queue completionHandler:^(NSURLResponse* response, NSData *data, NSError *connectionError){
NSString* content = [[NSString alloc] initWithData:data encoding: NSUTF8StringEncoding];
NSLog(@"内容: %@", content);
}];
同步方式(阻塞)
NSURL *url = [NSURL URLWithString :@"www.baidu.com"];
NSURLRequest *request = [NSURLRequest requestWithURL: url];
NSURLResponse *response = nil;
NSData *data = [NSURLConnection sendSynchronousRequest: request returningResponse: &response error:nil];
NSString* content = [[NSString alloc] initWithData:data encoding: NSUTF8StringEncoding];
NSLog(@"内容: %@", content);
监听会话过程的网络
NSURLSessionConfiguration *sessionConfig = [NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession *session = [NSURLSession sessionWithConfiguration:sessionConfig delegate:self delegateQueue:nil];
NSURLSessionDownloadTask *downloadTask = [session downloadTaskWithURL:[NSURL URLWithString:@"Your URL"]];
[downloadTask resume];
}
/*
当不再需要连接时,可以调用Session的invalidateAndCancel直接关闭,或者调用finishTasksAndInvalidate等待当前Task结束后关闭。这时Delegate会收到URLSession:didBecomeInvalidWithError:这个事件。Delegate收到这个事件之后会被解引用。
*/
- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didFinishDownloadingToURL:(NSURL *)location
{
NSData *data = [NSData dataWithContentsOfURL:location];
//Your code
[session finishTasksAndInvalidate];
}
- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask
didWriteData:(int64_t)bytesWritten totalBytesWritten:(int64_t)totalBytesWritten
totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite {
float progress = totalBytesWritten/ totalBytesExpectedToWrite;
dispatch_async(dispatch_get_main_queue(), ^{
self.progressView.progress = progress;
});
}
- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask
didResumeAtOffset:(int64_t)fileOffset expectedTotalBytes:(int64_t)expectedTotalBytes {
}
创建后台session, 随后使用这个session创建下载,并启动即可
- (NSURLSession *)createBackgroundSession {
static NSURLSession *session = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
NSURLSessionConfiguration *sessionConfiguration = [NSURLSessionConfiguration backgroundSessionConfiguration:@"<font color=#A52A2A>Your Idntification</font>"];
session = [NSURLSession sessionWithConfiguration:sessionConfiguration delegate:self delegateQueue:nil]; });
return session;
}
- 取消下载
-(IBAction)cancel:(id)sender
{
if(!self.downloadTask)
return;
[self.downloadTask cancelByProducingResumeData:(^NSData *resumeData){
if(!resumeData)
return;
[self setResumeData:resumeData];
[self setDownloadTask:nil];
}];
}
- 恢复下载
- (IBaction)resume:(id)sender
{
if(!self.resumeData) return;
self.downloadTask = [self.session downloadTaskWithResumeData:self.resumeData];
[self.downloadTask resume];
[self setResumeData:nil];
}
-(void)testPost{
NSURL *url = [NSURL URLWithString:@"http://yiyuyan.cc:666/post"];
NSString *str = [NSString stringWithFormat:@"action=%@&enctype=%@",@"post",@"multipart"];
NSMutableURLRequest *requestM = [NSMutableURLRequest requestWithURL:url];
requestM.HTTPMethod = @"POST";
requestM.HTTPBody = [str dataUsingEncoding:NSUTF8StringEncoding];
//普通的网络任务
NSURLSessionDataTask *task = [[NSURLSession sharedSession] dataTaskWithRequest:requestM completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
NSLog(@"%@",[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]) ;
}];
[task resume];
}
-(void)testGet{
//普通任务--get
//网络会话
NSURLSession *session = [NSURLSession sharedSession];
//网络任务
NSURL *url = [NSURL URLWithString:@"http://pan.baidu.com/disk/home#list/path=%2F"];
NSURLSessionDataTask *task = [session dataTaskWithURL:url completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
NSLog(@"data = %@",[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]);
}];
[task resume];
}