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

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

Core Foundation中NSURLConnection在2003年伴随着Safari浏览器的发行,诞生的时间比较久远,iOS升级比较快,AFNetWorking在3.0版本删除了所有基于NSURLConnection API的所有支持,新的API完全基于NSURLSession。AFNetworking 1.0建立在NSURLConnection的基础之上 ,AFNetworking 2.0使用NSURLConnection基础API,以及较新基于NSURLSession的API的选项。NSURLSession用于请求数据,作为URL加载系统,支持http,https,ftp,file,data协议。

基础知识

URL加载系统中需要用到的基础类:

iOS7和Mac OS X 10.9之后通过NSURLSession加载数据,调用起来也很方便: 

NSURL *url=[NSURL URLWithString:@"http://www.cnblogs.com/xiaofeixiang"];    NSURLRequest *urlRequest=[NSURLRequest requestWithURL:url];    NSURLSession *urlSession=[NSURLSession sharedSession];    NSURLSessionDataTask *dataTask=[urlSession dataTaskWithRequest:urlRequest completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {        NSDictionary *content = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];        NSLog(@"%@",content);    }];    [dataTask resume];

 

NSURLSessionTask是一个抽象子类,它有三个具体的子类是可以直接使用的:NSURLSessionDataTask,NSURLSessionUploadTask和NSURLSessionDownloadTask。这三个类封装了现代应用程序的三个基本网络任务:获取数据,比如JSON或XML,以及上传下载文件。dataTaskWithRequest方法用的比较多,关于下载文件代码完成之后会保存一个下载之后的临时路径:

NSURLSessionDownloadTask *downloadTask=[urlSession downloadTaskWithRequest:urlRequest completionHandler:^(NSURL * _Nullable location, NSURLResponse * _Nullable response, NSError * _Nullable error) {            }];

NSURLSessionUploadTask上传一个本地URL的NSData数据:

NSURLSessionUploadTask *uploadTask=[urlSession uploadTaskWithRequest:urlRequest fromData:[NSData new] completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {            }];

NSURLSession在Foundation中我们默认使用的block进行异步的进行任务处理,当然我们也可以通过delegate的方式在委托方法中异步处理任务,关于委托常用的两种NSURLSessionTaskDelegate和NSURLSessionDownloadDelegate,其他的关于NSURLSession的委托有兴趣的可以看一下API文档,首先我们需要设置delegate:

NSURLSessionConfiguration *sessionConfig = [NSURLSessionConfiguration defaultSessionConfiguration];    NSURLSession *inProcessSession = [NSURLSession sessionWithConfiguration:sessionConfig delegate:self delegateQueue:nil];    NSString *url = @"http://www.cnblogs.com/xiaofeixiang";    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:url]];    NSURLSessionTask *dataTask = [inProcessSession dataTaskWithRequest:request];    [dataTask resume];

任务下载的设置delegate:

NSURLSessionConfiguration *sessionConfig = [NSURLSessionConfiguration defaultSessionConfiguration];    NSURLSession *inProcessSession = [NSURLSession sessionWithConfiguration:sessionConfig delegate:self delegateQueue:nil];    NSString *url = @"http://www.cnblogs.com/xiaofeixiang";    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:url]];    NSURLSessionDownloadTask *downloadTask = [inProcessSession downloadTaskWithRequest:request];    [downloadTask resume];

关于delegate中的方式只实现其中的两种作为参考:

#pragma mark - NSURLSessionDownloadDelegate-(void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didFinishDownloadingToURL:(NSURL *)location{    NSLog(@"NSURLSessionTaskDelegate--下载完成");}#pragma mark - NSURLSessionTaskDelegate-(void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error{     NSLog(@"NSURLSessionTaskDelegate--任务结束");}

NSURLSession状态同时对应着多个连接,不能使用共享的一个全局状态,会话是通过工厂方法来创建配置对象。

defaultSessionConfiguration(默认的,进程内会话),ephemeralSessionConfiguration(短暂的,进程内会话),backgroundSessionConfigurationWithIdentifier(后台会话)

第三种设置为后台会话的,当任务完成之后会调用application中的方法:

-(void)application:(UIApplication *)application handleEventsForBackgroundURLSession:(NSString *)identifier completionHandler:(void (^)())completionHandler{    }

网络封装

上面的基础知识能满足正常的开发,我们可以对常见的数据get请求,Url编码处理,动态添加参数进行封装,其中关于url中文字符串的处理

stringByAddingPercentEncodingWithAllowedCharacters属于新的方式,字符允许集合选择的是URLQueryAllowedCharacterSet,

NSCharacterSet中分类有很多,详细的可以根据需求进行过滤~

typedef void (^CompletioBlock)(NSDictionary *dict, NSURLResponse *response, NSError *error);@interface FENetWork : NSObject+(void)requesetWithUrl:(NSString *)url completeBlock:(CompletioBlock)block;+(void)requesetWithUrl:(NSString *)url params:(NSDictionary *)params completeBlock:(CompletioBlock)block;@end

 

@implementation FENetWork+(void)requesetWithUrl:(NSString *)url completeBlock:(CompletioBlock)block{    NSString *urlEnCode=[url stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];    NSURLRequest *urlRequest=[NSURLRequest requestWithURL:[NSURL URLWithString:urlEnCode]];    NSURLSession *urlSession=[NSURLSession sharedSession];    NSURLSessionDataTask *dataTask=[urlSession dataTaskWithRequest:urlRequest completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {        if (error) {            NSLog(@"%@",error);            block(nil,response,error);        }else{            NSDictionary *content = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];            block(content,response,error);        }    }];    [dataTask resume];}+(void)requesetWithUrl:(NSString *)url params:(NSDictionary *)params completeBlock:(CompletioBlock)block{        NSMutableString *mutableUrl=[[NSMutableString alloc]initWithString:url];    if ([params allKeys]) {        [mutableUrl appendString:@"?"];        for (id key in params) {            NSString *value=[[params objectForKey:key] stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];            [mutableUrl appendString:[NSString stringWithFormat:@"%@=%@&",key,value]];        }    }    [self requesetWithUrl:[mutableUrl substringToIndex:mutableUrl.length-1] completeBlock:block];}@end

参考资料:https://developer.apple.com/library/prerelease/mac/documentation/Cocoa/Reference/Foundation/Classes/NSCharacterSet_Class/index.html#//apple_ref/occ/clm/NSCharacterSet/URLQueryAllowedCharacterSet

博客同步至:

转载于:https://www.cnblogs.com/xiaofeixiang/p/5153247.html

你可能感兴趣的文章
linux多线程示例
查看>>
java日期和字符串的相互转换
查看>>
如何给caffe添加新的layer ?
查看>>
数据库连接池
查看>>
植物 miRNA 研究
查看>>
分布式交易系统的并发处理, 以及用Redis和Zookeeper实现分布式锁
查看>>
http 304优化,了解客户端缓存
查看>>
SQLite(轻量级最佳数据库) 原理分析和开发应用zz
查看>>
改善用户体念:Jquery实现td tr单击事件(input事件)
查看>>
GridView标头居中,内容居中
查看>>
asp.net datatable中行的复制
查看>>
在Eclipse中安装ADT
查看>>
三十七、android sqlite3详解
查看>>
Open Build Service
查看>>
UVA 696 How Many Knights
查看>>
[更新]Luke.Net for Pangu 盘古分词版更新
查看>>
jsp 生成静态页面
查看>>
ipad 使用UIImageView显示网络上的图片
查看>>
转: std::string用法详解
查看>>
【入门经典】Master和Content页面之一
查看>>