iOS开发-NSURLSession详解
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
博客同步至:我的简书博客
iOS开发-NSURLSession详解的更多相关文章
- iOS开发——Block详解
iOS开发--Block详解 1. Block是什么 代码块 匿名函数 闭包--能够读取其他函数内部变量的函数 函数变量 实现基于指针和函数指针 实现回调的机制 Block是一个非常有特色的语法,它可 ...
- iOS开发:详解Objective-C runTime
Objective-C总Runtime的那点事儿(一)消息机制 最近在找工作,Objective-C中的Runtime是经常被问到的一个问题,几乎是面试大公司必问的一个问题.当然还有一些其他问题也几乎 ...
- iOS开发-Runtime详解
iOS开发-Runtime详解 简介 Runtime 又叫运行时,是一套底层的 C 语言 API,其为 iOS 内部的核心之一,我们平时编写的 OC 代码,底层都是基于它来实现的.比如: [recei ...
- iOS开发——MVC详解&Swift+OC
MVC 设计模式 这两天认真研究了一下MVC设计模式,在iOS开发中这个算是重点中的重点了,如果对MVC模式不理解或者说不会用,那么你iOS肯定学不好,或者写不出好的东西,当然本人目前也在学习中,不过 ...
- IOS开发之----详解在IOS后台执行
文一 我从苹果文档中得知,一般的应用在进入后台的时候可以获取一定时间来运行相关任务,也就是说可以在后台运行一小段时间. 还有三种类型的可以运行在后以,1.音乐2.location 3.voip 文二 ...
- iOS开发--Bison详解连连支付集成简书
"最近由于公司项目需要集成连连支付,文档写的不是很清楚,遇到了一些坑,因此记录一下,希望能帮到有需要的人." 前面简单的集成没有遇到什么坑,在此整理一下官方的集成文档,具体步骤如下 ...
- iOS开发之详解正则表达式
本文由Charles翻自raywenderlich原文:NSRegularExpression Tutorial: Getting Started更新提示:本教程被James Frost更新到了iOS ...
- iOS开发-Runtime详解(简书)
简介 Runtime 又叫运行时,是一套底层的 C 语言 API,其为 iOS 内部的核心之一,我们平时编写的 OC 代码,底层都是基于它来实现的.比如: [receiver message]; // ...
- iOS开发-UITabBarController详解
我们在开发中经常会使用到UITabBarController来布局App应用,使用UITabBarController可以使应用看起来更加的清晰,iOS系统的闹钟程序,ipod程序都是非常好的说明和A ...
随机推荐
- Azure DW
1. 安装环境a. 安装环境https://www.microsoft.com/web/downloads/platform.aspx b. InputImport-Module 'C:\Progra ...
- IIS mime类型 任意类型
HTTP头 任意mime类型 .* application/octet-stream
- Missing letters
function fearNotLetter(str) { //return str; var arr = str.split(''); var temp = []; var start = str. ...
- 技术英文单词贴--R
R redirect 重定向,改变方向 reference 参考,提及,引用 register 注册,登记,挂号 render 渲染 represent 代表,象征 route 路线,路由,通道 ro ...
- GRUB密码设置
通过编辑GRUB启动参数可以轻松的进入单用户模式从而修改root密码,GRUB的密码设置可分为全局密码和菜单密码. 一,全局密码设置 在splashimage这个参数的下一行可以加上passw ...
- coursera 机器学习课程 GraphLab环境准备
在网上看到coursera有机器学习的课程,正好再学习学习,温固一下,还有很多其他的课程也很好.收费的哟! 手机APP和网站收取的费用有差异,网站上要便宜一下,费用差的挺多的,果断在网站上支付了. 有 ...
- hdu 5748(LIS) Bellovin
hdu 5748 Peter有一个序列a1,a2,...,ana_1,a_2,...,a_na1,a2,...,an. 定义F(a1,a2,...,an)=(f1,f2,...,fn ...
- RAID配置
一.madam -a 检测设备名称 -n 指定硬盘数量 -l 指定raid级别 -C 创建 -f 模拟硬盘故障 -r 移除硬盘 -a ...
- zabbix告警“Zabbix poller processes more than 75% busy”
告警原因: 1.某个进程卡住了, 2.僵尸进程出错,太多,导致慢了 3.网络延迟(可忽略) 4.zabbix消耗的内存多了 告警危害: 普通告警,暂无危害(但是最好处理) 处理方法: 一:简单,粗暴( ...
- Xcode7.2 导入XMPP框架错误解决
1.修改Build Settings 在 Header Search Paths 中添加: "/usr/include/libxml2" 在Other Linker Flags 中 ...