博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
NSURLSession详解
阅读量:4703 次
发布时间:2019-06-09

本文共 9213 字,大约阅读时间需要 30 分钟。

导语

  • 现在NSURLConnection在开发中会使用的越来越少,iOS9已经将NSURLConnection废弃,现在最低版本一般适配iOS7,所以也可以使用。

  • NSURLConnection相对于NSURLSession,安全性低。NSURLConnection下载有峰值,比较麻烦处理。
  • 尽管适配最低版本iOS7,也可以使用NSURLSession。AFN已经不支持NSURLConnection。
  •  NSURLSession:默认是挂起状态,如果要请求网络,需要开启。

     [NSURLSession sharedSession] 获取全局的NSURLSession对象。在iPhone的所有app共用一个全局session.

     NSURLSessionUploadTask -> NSURLSessionDataTask -> NSURLSessionTask
     NSURLSessionDownloadTask -> NSURLSessionTask
     NSURLSessionDownloadTask下载,默认下载到tmp文件夹。下载完成后删除临时文件。所以我们要在删除文件之前,将它移动到Cache里。

NSURLSession详解

  1. NSURLSession基础

  2. NSURLSession代理
  3. NSURLSession大文件下载
  4. NSURLSession断点续传

1.NSURLSession基础

  • 第一种网络请求方法  
//创建URL    NSURL * url = [NSURL URLWithString:@"http://192.168.1.200/login.php?username=haha&password=123"];    //创建请求    //    NSURLRequest * request = [NSURLRequest requestWithURL:url];    //创建Session    NSURLSession * session = [NSURLSession sharedSession];    //创建任务    NSURLSessionDataTask * task = [session dataTaskWithURL:url completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {        NSLog(@"%@",[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]);    }];    //开启网络任务    [task resume];
  • 第二种网络请求方法
//创建URL    NSURL * url = [NSURL URLWithString:@"http://192.168.1.200/login.php?username=haha&password=123"];    //创建请求    NSURLRequest * request = [NSURLRequest requestWithURL:url];    //创建Session    NSURLSession * session = [NSURLSession sharedSession];    //创建任务    NSURLSessionDataTask * task = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {        NSLog(@"%@",[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]);            }];    //开启网络任务    [task resume];
  • POST请求
NSURL * url = [NSURL URLWithString:@"http://192.168.1.200/login.php"];        NSMutableURLRequest * request = [NSMutableURLRequest requestWithURL:url];        //设置请求方法    request.HTTPMethod = @"POST";        //设置请求体    request.HTTPBody = [@"username=haha&password=123" dataUsingEncoding:NSUTF8StringEncoding];        [[[NSURLSession sharedSession] dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {                NSLog(@"%@",[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]);            }] resume];
  • 下载文件
NSURL * url = [NSURL URLWithString:[@"http://192.168.1.200/DOM解析.mp4" stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];        NSURLSession * session = [NSURLSession sharedSession];    NSURLSessionDownloadTask * downloadTask = [session downloadTaskWithURL:url completionHandler:^(NSURL * _Nullable location, NSURLResponse * _Nullable response, NSError * _Nullable error) {                //location 下载到沙盒的地址        NSLog(@"下载完成%@",location);            //response.suggestedFilename 响应信息中的资源文件名        NSString * cachesPath = [[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:response.suggestedFilename];                NSLog(@"缓存地址%@",cachesPath);                //获取文件管理器        NSFileManager * mgr = [NSFileManager defaultManager];        //将临时文件移动到缓存目录下        //[NSURL fileURLWithPath:cachesPath] 将本地路径转化为URL类型        //URL如果地址不正确,生成的url对象为空                [mgr moveItemAtURL:location toURL:[NSURL fileURLWithPath:cachesPath] error:NULL];            }];        [downloadTask resume];

2.NSURLSession代理

 

- (void)touchesBegan:(NSSet
*)touches withEvent:(UIEvent *)event { // 全局session // NSURLSession * session = [NSURLSession sharedSession]; //创建自定义session //NSURLSessionConfiguration 的 配置 //[[NSOperationQueue alloc] init] 也可以写成 nil NSURL * url = [NSURL URLWithString:@"http://192.168.1.200/login.php?username=haha&password=123"]; NSURLSession * session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration] delegate:self delegateQueue:[[NSOperationQueue alloc] init]]; NSURLSessionDataTask * task = [session dataTaskWithURL:url]; [task resume]; }//接收到服务器响应- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTaskdidReceiveResponse:(NSURLResponse *)response completionHandler:(void (^)(NSURLSessionResponseDisposition disposition))completionHandler { NSLog(@"%s",__FUNCTION__); //允许接受服务器回传数据 completionHandler(NSURLSessionResponseAllow);}//接收服务器回传的数据,有可能执行多次- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveData:(NSData *)data { NSLog(@"%@",[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]);}//请求成功或失败- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error { NSLog(@"%@",error);}

 

3.NSURLSession大文件下载

 

#import "ViewController.h"@interface ViewController ()
@end@implementation ViewController- (void)viewDidLoad { [super viewDidLoad]; // Do any additional setup after loading the view, typically from a nib. NSLog(@"%@",NSSearchPathForDirectoriesInDomains(9, 1, 1));}- (void)touchesBegan:(NSSet
*)touches withEvent:(UIEvent *)event { NSURLSession * session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration] delegate:self delegateQueue:[[NSOperationQueue alloc] init]]; NSURLSessionDownloadTask * task = [session downloadTaskWithURL:[NSURL URLWithString:[@"http://192.168.1.200/DOM解析.mp4"stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]]]; [task resume];}/* 监测临时文件下载的数据大小,当每次写入临时文件时,就会调用一次 bytesWritten 单次写入多少 totalBytesWritten 已经写入了多少 totalBytesExpectedToWrite 文件总大小 */- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didWriteData:(int64_t)bytesWritten totalBytesWritten:(int64_t)totalBytesWrittentotalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite { //打印下载百分比 NSLog(@"%f",totalBytesWritten * 1.0 / totalBytesExpectedToWrite); }//下载完成- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTaskdidFinishDownloadingToURL:(NSURL *)location { NSString * cachesPath = [[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:downloadTask.response.suggestedFilename]; NSFileManager * mgr = [NSFileManager defaultManager]; [mgr moveItemAtURL:location toURL:[NSURL fileURLWithPath:cachesPath] error:NULL]; }- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error { NSLog(@"%@",error);}

 

4.NSURLSession断点续传

 

#import "ViewController.h"@interface ViewController ()
@property (nonatomic, strong) NSURLSessionDownloadTask * task;@property (nonatomic, strong) NSData * resumeData;@property (nonatomic, strong) NSURLSession * session;@end@implementation ViewController//故事板中开始按钮的响应方法- (IBAction)start:(id)sender { NSURLSession * session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration] delegate:self delegateQueue:[[NSOperationQueue alloc] init]]; self.session = session; self.task = [session downloadTaskWithURL:[NSURL URLWithString:[@"http://192.168.1.68/丁香花.mp3"stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]]]; [self.task resume];}//故事板中暂停按钮的响应方法- (IBAction)pause:(id)sender { //暂停就是将任务挂起 [self.task cancelByProducingResumeData:^(NSData *resumeData) { //保存已下载的数据 self.resumeData = resumeData; }];}//继续按钮的响应方法- (IBAction)resume:(id)sender { //可以使用ResumeData创建任务 self.task = [self.session downloadTaskWithResumeData:self.resumeData]; //开启继续下载 [self.task resume]; }- (void)viewDidLoad { [super viewDidLoad]; // Do any additional setup after loading the view, typically from a nib. NSLog(@"%@",NSSearchPathForDirectoriesInDomains(9, 1, 1));}/* 监测临时文件下载的数据大小,当每次写入临时文件时,就会调用一次 bytesWritten 单次写入多少 totalBytesWritten 已经写入了多少 totalBytesExpectedToWrite 文件总大小 */- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didWriteData:(int64_t)bytesWritten totalBytesWritten:(int64_t)totalBytesWrittentotalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite { //打印下载百分比 NSLog(@"%f",totalBytesWritten * 1.0 / totalBytesExpectedToWrite); }//下载完成- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTaskdidFinishDownloadingToURL:(NSURL *)location { NSString * cachesPath = [[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:downloadTask.response.suggestedFilename]; NSFileManager * mgr = [NSFileManager defaultManager]; [mgr moveItemAtURL:location toURL:[NSURL fileURLWithPath:cachesPath] error:NULL]; }- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error { NSLog(@"%@",error);}

 

转载于:https://www.cnblogs.com/ldnh/p/5304279.html

你可能感兴趣的文章
633. 寻找重复的数
查看>>
沉淀,再出发:python中的pandas包
查看>>
Rule 12: Remove Duplicate Scripts(Chapter 12 of High performance Web Sites)
查看>>
操作redis数据库 & 操作Excel & 开发接口
查看>>
framework7 点取消后还提交表单解决方案
查看>>
JAVA Axis2调用WebService
查看>>
js学习---常用的内置对象(API)小结 :
查看>>
付费版百度指数 就是这么坑爹
查看>>
uva 116 Unidirectional TSP【号码塔+打印路径】
查看>>
关于android的2.2与4.4的文件读取的一点发现
查看>>
关于MAC的pkg和mpkg的分别
查看>>
11. 尽可能减少DB2的SQL请求
查看>>
MVC图片上传
查看>>
Hive优化(转)
查看>>
Android获取服务器Json字符串并显示在ListView上面
查看>>
4-13 杂记
查看>>
配置Spring数据源c3p0与dbcp
查看>>
uitabbarcontroller中 在设置tab bar item的image属性后不显示问题
查看>>
MVC静态化
查看>>
『MXNet』第十二弹_再谈新建计算节点
查看>>