[置顶] NSURLSessionTask、NSURLSessionDataTask、NSURLSessionDownloadTask类分析

前言:从iOS9.0开始,苹果开发文档里已明确指出NSURLConnection不建议使用(原话是:DEPRECATED: The NSURLConnection class should no longer be used.  

NSURLSession is the replacement for NSURLConnection)。
使用NSURLSession处理网络请求,我先罗列下涉及的相关类:
NSURLSession、NSURLSessionConfiguration
NSURLSessionTask、NSURLSessionDataTask、NSURLSessionUploadTask、NSURLSessionDownloadTask
NSURLSessionDelegate、NSURLSessionTaskDelegate、NSURLSessionDataDelegate、NSURLSessionDownloadDelegate。

使用NSURLSession实现网络请求的一般步骤如下: 
1. 定义一个NSURLRequest或NSURL
2. 定义一个NSURLSessionConfiguration,配置各种网络参数
3. 使用NSURLSession的工厂方法获取一个所需类型的NSURLSession
4. 使用定义好的NSURLRequest或NSURL和NSURLSession创建一个NSURLSessionTask
5. 使用Delegate或者CompletionHandler处理任务执行过程的所有事件。

本文介绍在网络请求中,需要使用NSURLSessionTask的类方法或成员方法(至于NSURLSessionDataTask、NSURLSessionUploadTask、NSURLSessionDownloadTask,虽是他的子类,但功能基本并没有扩充)。


The NSURLSessionTask class is the base class for tasks in a URL session. Tasks are always part of a session;  you create a task by calling one of the task creation methods on an NSURLSession object. The method you call determines the type of task.

URL sessions provide three types of tasks: data tasks, upload tasks, and download tasks.
These tasks are instances of the NSURLSessionDataTask, NSURLSessionUploadTask, and NSURLSessionDownloadTask subclasses of NSURLSessionTask, respectively.

Data tasks request a resource, returning the server’s response as one or more NSData objects in memory. They are supported in default, ephemeral, and shared sessions, but are not supported in background sessions.

Upload tasks are like data tasks, except that they make it easier to provide a request body so you can upload data before retrieving the server’s response. Additionally, upload tasks are supported in background sessions.

Download tasks download a resource directly to a file on disk. Download tasks are supported in any type of session. 

After you create a task, you start it by calling its resume method. The session then maintains a strong reference to the task until the request finishes or fails; you do not need to maintain a reference to the task unless it is useful to do so for your app’s internal bookkeeping purposes.

我将通过封装断点续传,向大家演示NSURLSessionDataTask的使用。至于其他NSURLSessionTask子类的使用不再说明。







你可能感兴趣的:(网络请求,开发,文档,苹果,NSURLSession)