iOS网络编程(NSURLConnection &&am
NSURLSession优点:
后台下载和上传:
停止和继续网络操作
可配置的容器 --- 在同一session的所有请求中,只需要设置一次HTTP头
可子类化和私有仓库
提升验证处理 --- delegate处理验证
富代理模型
通过文件系统上传和下载
�NSURLSession VS NSURLConnection
对于简单任务,NSURLSession要比NSURLConnection用起来简单。下面例子是获取JSON格式的关于最新的北京天气:


NSURLSession VS AFNetworking

ps:教程中的AFJSONRequestOperation在AF 1.x当中才有,已经被淘汰,所以用AF 2.x的方法来发送网络请求
与NSURLSession相比,能够提前设置AFJSONResponseSerializer,返回数据直接是JSON,而NSURLSession返回NSData,需要自己解析。
结论:
对于简单的需求用NSURLSession,避免引入第三方库。
NSURLSession 类 --- 上传,下载,处理验证和HTTP协议中的事情

a) NSURLSessionConfiguration
三种方法创建:
1) defaultSessionConfiguration:用全局缓存,cookie和证书存储对象,这种方式使得session像NSURLConnection
2) ephemeralSessionConfiguration:为了私有session,没有持久的缓存,cookie和证书
3) backgroundSessionConfiguration:当来自远程推送通知和app暂时的时候,发送网络请求

b) NSURLSession
用来替代NSURLConnection,NSURLSessionTask用来做很多事情,用基于便利方法的block创建tasks,设置delegate。如果要下载图片,需要创建NSURLSessionDownloadTask。
准备工作:

两种方法 --- (1) 直接block回调 (2) 创建 + delegate方法回调
(1)

(2)


追踪下载进度:

c) NSURLSessionTask

<1> NSURLSessionDataTask
涉及HTTP GET请求,从服务器下载数据。以NSData形式返回。自己转换。

<2> NSURLSessionUploadTask
用HTTP POST or PUT上传,delegate方法追踪上传进度

<3> NSURLSessionDownloadTask
与其他两个子类有点不同:
i) 这种类型的task直接写为一个临时文件
ii) 当下载session被调用期间 URLSession:downloadTask:didWriteData: totalBytesWritten: totalBytesExpectedToWrite:更新状体信息。
iii) 当任务完成,URLSession:downloadTask:didFinishDownloadingToURL:被调用,这样可以保存文件从临时的到持久
iv) 当下载失败或者取消, 获得数据继续下载
Tip:
task Identifier 唯一标识一个task,用于管理多task的时候。
以上所有创建之后都是暂停状态,必须调用 resume 才能调用。
Let's play
(1) 首先创建NSURLSession

(2) 获取列表


Tip:作为使用IB的参考
StoryBoard跳转一般用 prepareForSegue:sender: 方法,传递session,作为delegate;当用户完成编辑或者取消编辑时,NoteDetailsViewController能够通知NoteViewController。

(3) 增加 Cancel 和 Done 功能

(4) 获取详细内容

上传大文件并观察进度,这种异步,耗时任务需要实现协议方法NSURLSessionTaskDelegate,任务获得数据和完成获得回调。
(5) 设置图片 -- 下载图片,异步更新UI

(6) 刷新图片 -- 与前面的请求相似


(7) 上传图片 -- 实现 NSURLSessionDelegate && NSURLSessionTaskDelegate 协议获得回调

(8) delegate方法

(8.5) 下载完成delegate 方法

(9) 取消下载

引文: