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加载数据,调用起来也很方便:

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

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

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

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

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

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

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

任务下载的设置delegate:

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

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

  1. #pragma mark - NSURLSessionDownloadDelegate
  2. -(void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didFinishDownloadingToURL:(NSURL *)location{
  3. NSLog(@"NSURLSessionTaskDelegate--下载完成");
  4. }
  5.  
  6. #pragma mark - NSURLSessionTaskDelegate
  7. -(void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error{
  8. NSLog(@"NSURLSessionTaskDelegate--任务结束");
  9. }

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

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

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

  1. -(void)application:(UIApplication *)application handleEventsForBackgroundURLSession:(NSString *)identifier completionHandler:(void (^)())completionHandler{
  2.  
  3. }

网络封装

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

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

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

  1. typedef void (^CompletioBlock)(NSDictionary *dict, NSURLResponse *response, NSError *error);
  2.  
  3. @interface FENetWork : NSObject
  4.  
  5. +(void)requesetWithUrl:(NSString *)url completeBlock:(CompletioBlock)block;
  6.  
  7. +(void)requesetWithUrl:(NSString *)url params:(NSDictionary *)params completeBlock:(CompletioBlock)block;
  8.  
  9. @end
  1. @implementation FENetWork
  2.  
  3. +(void)requesetWithUrl:(NSString *)url completeBlock:(CompletioBlock)block{
  4. NSString *urlEnCode=[url stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
  5. NSURLRequest *urlRequest=[NSURLRequest requestWithURL:[NSURL URLWithString:urlEnCode]];
  6. NSURLSession *urlSession=[NSURLSession sharedSession];
  7. NSURLSessionDataTask *dataTask=[urlSession dataTaskWithRequest:urlRequest completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
  8. if (error) {
  9. NSLog(@"%@",error);
  10. block(nil,response,error);
  11. }else{
  12. NSDictionary *content = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
  13. block(content,response,error);
  14. }
  15. }];
  16. [dataTask resume];
  17. }
  18.  
  19. +(void)requesetWithUrl:(NSString *)url params:(NSDictionary *)params completeBlock:(CompletioBlock)block{
  20.  
  21. NSMutableString *mutableUrl=[[NSMutableString alloc]initWithString:url];
  22. if ([params allKeys]) {
  23. [mutableUrl appendString:@"?"];
  24. for (id key in params) {
  25. NSString *value=[[params objectForKey:key] stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
  26. [mutableUrl appendString:[NSString stringWithFormat:@"%@=%@&",key,value]];
  27. }
  28. }
  29. [self requesetWithUrl:[mutableUrl substringToIndex:mutableUrl.length-1] completeBlock:block];
  30. }
  31.  
  32. @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详解的更多相关文章

  1. iOS开发——Block详解

    iOS开发--Block详解 1. Block是什么 代码块 匿名函数 闭包--能够读取其他函数内部变量的函数 函数变量 实现基于指针和函数指针 实现回调的机制 Block是一个非常有特色的语法,它可 ...

  2. iOS开发:详解Objective-C runTime

    Objective-C总Runtime的那点事儿(一)消息机制 最近在找工作,Objective-C中的Runtime是经常被问到的一个问题,几乎是面试大公司必问的一个问题.当然还有一些其他问题也几乎 ...

  3. iOS开发-Runtime详解

    iOS开发-Runtime详解 简介 Runtime 又叫运行时,是一套底层的 C 语言 API,其为 iOS 内部的核心之一,我们平时编写的 OC 代码,底层都是基于它来实现的.比如: [recei ...

  4. iOS开发——MVC详解&Swift+OC

    MVC 设计模式 这两天认真研究了一下MVC设计模式,在iOS开发中这个算是重点中的重点了,如果对MVC模式不理解或者说不会用,那么你iOS肯定学不好,或者写不出好的东西,当然本人目前也在学习中,不过 ...

  5. IOS开发之----详解在IOS后台执行

    文一 我从苹果文档中得知,一般的应用在进入后台的时候可以获取一定时间来运行相关任务,也就是说可以在后台运行一小段时间. 还有三种类型的可以运行在后以,1.音乐2.location 3.voip 文二 ...

  6. iOS开发--Bison详解连连支付集成简书

    "最近由于公司项目需要集成连连支付,文档写的不是很清楚,遇到了一些坑,因此记录一下,希望能帮到有需要的人." 前面简单的集成没有遇到什么坑,在此整理一下官方的集成文档,具体步骤如下 ...

  7. iOS开发之详解正则表达式

    本文由Charles翻自raywenderlich原文:NSRegularExpression Tutorial: Getting Started更新提示:本教程被James Frost更新到了iOS ...

  8. iOS开发-Runtime详解(简书)

    简介 Runtime 又叫运行时,是一套底层的 C 语言 API,其为 iOS 内部的核心之一,我们平时编写的 OC 代码,底层都是基于它来实现的.比如: [receiver message]; // ...

  9. iOS开发-UITabBarController详解

    我们在开发中经常会使用到UITabBarController来布局App应用,使用UITabBarController可以使应用看起来更加的清晰,iOS系统的闹钟程序,ipod程序都是非常好的说明和A ...

随机推荐

  1. ssh搭建后的简化

    关于ssh如何搭建还有不懂得朋友可以参考以下网址:http://www.cnblogs.com/LarryBlogger/p/5841446.html 在这里我就不重复再讲了! ssh搭建后的简化 简 ...

  2. 边表+SPFA (使用指针+动态内存)

    233 只是我怕忘了怎么写指针操作 所以写一遍指针版的 然而洛谷评测机不给力,400多ms过了数组的,600多ms过指针的... 我想,指针的比数组的理解起来应该容易一点吧 戳我是数组版的,NOIP时 ...

  3. 利用ASP.NET加密和解密Web.config中连接字符串

    摘自:博客园 介绍 这篇文章我将介绍如何利用ASP.NET来加密和解密Web.config中连接字符串 背景描述 在以前的博客中,我写了许多关于介绍 Asp.net, Gridview, SQL Se ...

  4. hibernate多表查询,结果封装在自己定义的一个实体类当中(在自己定义的类中增加构造函数)

    hibernate的hql查询直接返回java对象时出现问题3 向大家请教一个问题,现在有三张表,表之间没有关联,我需要将三张表里面的所有东西查询出来存储到一个新的对象中,该如何实现,使用hibern ...

  5. 使用VPN服务器解决公司不能上淘宝的问题

    很多公司为了保证员工的效率,通常采用屏蔽端口的方法屏蔽掉了一些网站,比如淘宝.QQ网页版等,这样做虽然也是公司的迫不得已,但是也有点不人性化,毕竟非上班时间也是上不去此类网站的.前些日子电商大站,抢不 ...

  6. Unity3D 中 用quaternion 来对一个坐标点进行旋转的初步体会

    在unity3d中,用四元数来表示旋转,四元数英文名叫quaternion . 比如 transform.rotation 就是一个四元数,其由四个部分组成 Quaternion = (xi + yj ...

  7. Java 第五章 循环结构1

    循环结构 1 while 循环结构 ,do- while 循环结构 . 循环结构: 必须满足两个条件 . 1,循环条件 和 循环 操作 ! while 循环 特点:先判断,再执行 , 编码规范:缩进, ...

  8. Redis在CentOS6.4中的安装

    首先,介绍一下Redis数据库.Redis是一种面向“键/值”对数据类型的内存数据库,可以满足我们对海量数据的读写需求. 1)redis的键只能是字符串: 2)redis的值支持多种数据类型: a:字 ...

  9. maven工程引用外部jar包

    maven工程经常回遇到引用外部jar包,需要先安装在jar包,然后再在工程中pom.xml文件中添加依赖. 示例: 命令行中运行: mvn install:install-file -Dfile=E ...

  10. iOS 开发者必知的 75 个工具(译文)

    原文地址:http://benscheirman.com/2013/08/the-ios-developers-toolbelt (需FQ)   如果你去到一位熟练的木匠的工作室,你总是能发现他/她有 ...