[置顶] NSURLSession类分析


前言:从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处理任务执行过程的所有事件。


本文介绍在网络请求中,需要使用NSURLSession的类方法或成员方法

获取NSURLSession对象的方式有三种
/*
返回一个共享的单实例会话对象(注意是单实例,就创建了一次),该对象使用全局的缓存、cookie存储、证书存储对象,使用默认配置。
Returns a shared singleton session object.
The shared session uses the currently set global NSURLCache, NSHTTPCookieStorage, and NSURLCredentialStorage objects and is based on the default configuration.
*/

+ (NSURLSession *)sharedSession;

/*
 Customization of NSURLSession occurs during creation of a new session.
 If you only need to use the convenience routines with custom
 configuration options it is not necessary to specify a delegate.
  
 Creates a session with the specified session configuration.
 A configuration object that specifies certain behaviors, such as caching policies, 
 timeouts, proxies, pipelining, TLS versions to support, cookie policies, credential  
 storage, and so on.
 */

+ (NSURLSession *)sessionWithConfiguration:(NSURLSessionConfiguration *)configuration;

/*
 Customization of NSURLSession occurs during creation of a new session.
 If you do specify a delegate, the delegate will be retained until after
 the delegate has been sent the URLSession:didBecomeInvalidWithError: message.
 
 Creates a session with the specified session configuration, delegate, and operation  
 queue.
 
 configuration
 A configuration object that specifies certain behaviors, such as caching policies,  
 timeouts, proxies, pipelining, TLS versions to support, cookie policies, and credential 
 storage.
 Because the session copies the configuration object, it is safe to modify the  
 configuration object and use it to construct additional sessions.

 delegate
 A session delegate object that handles requests for authentication and other  
 session-related events.
 This delegate object is responsible for handling authentication challenges, for making 
 caching decisions, and for handling other session-related events. If nil, the class uses  
 a system-provided delegate and should be used only with methods that take completion  
 handlers.
 
 Important:Important
 The session object keeps a strong reference to the delegate until your app explicitly  
 invalidates the session. If you do not invalidate the session by calling the 
 invalidateAndCancel or resetWithCompletionHandler: method, your app leaks memory.

 queue
 A queue for scheduling the delegate calls and completion handlers. If nil, the session  
 creates a serial operation queue for performing all delegate method calls and completion 
 handler calls.被调用的代理方法在队列生成的线程上串行执行,可能在同一个线程,也可能在不同的线程上。有界面处理的必须放在主线程上。
 
 */

+ (NSURLSession *)sessionWithConfiguration:(NSURLSessionConfiguration *)configuration delegate:(nullable id <NSURLSessionDelegate>)delegate delegateQueue:(nullable NSOperationQueue *)queue;

常用实例方法
/*
Invalidates the object, allowing any outstanding tasks to finish.
This method returns immediately without waiting for tasks to finish. 
Once a session is invalidated, new tasks cannot be created in the session, but existing tasks continue until completion. After the last task finishes and the session makes the last delegate call, references to the delegate and callback objects are broken. 
Session objects cannot be reused.
调用这个方法后,如果当前有,没有完成的请求任务,这些请求任务会继续,直到所有请求任务完成后,才会使session对象无效。
*/

- (void)finishTasksAndInvalidate;

/*
Cancels all outstanding tasks and then invalidates the session object.
Once invalidated, references to the delegate and callback objects are broken. Session objects cannot be reused.
调用这个方法后,取消所有正在执行的请求任务,然后使session对象无效。
*/

- (void)invalidateAndCancel;

/*
Resets the session asynchronously.
The completion handler to call when the reset operation is complete. This handler is executed on the delegate queue.

completionHandler
The completion handler to call when the reset operation is complete. This handler is executed on the delegate queue.
调用这个方法后,如果当前有,没有完成的请求任务,这些请求任务会继续,直到所有请求任务完成后,才会使session对象无效。
*/

- (void)resetWithCompletionHandler:(void (^)(void))completionHandler;

/* 
Creates a data task with the given request.  The request may have a body stream. 

request
An object that provides request-specific information such as the URL, cache policy, request type, and body data or body stream.
*/

- (NSURLSessionDataTask *)dataTaskWithRequest:(NSURLRequest *)request;

/* 
Creates a data task to retrieve the contents of the given URL. 
The task is an HTTP GET request for the specified URL.

url
The http or https URL to be retrieved.
*/

- (NSURLSessionDataTask *)dataTaskWithURL:(NSURL *)url;

/* 
Creates a download task with the given request and saves the results to a file.

request
An NSURLRequest object that provides the URL, cache policy, request type, body data or body stream, and so on.
*/

- (NSURLSessionDownloadTask *)downloadTaskWithRequest:(NSURLRequest *)request;

/* 
Creates a download task to download the contents of the given URL and saves the results to a file.

url
An NSURL object that provides the URL to download.
*/

- (NSURLSessionDownloadTask *)downloadTaskWithURL:(NSURL *)url;

/* 
Creates a download task with the resume data because of previously canceled or failed download. 
If the download cannot be successfully resumed, URLSession:task:didCompleteWithError: will be called. 

resumeData
A data object that provides the data necessary to resume a download.
*/

- (NSURLSessionDownloadTask *)downloadTaskWithResumeData:(NSData *)resumeData;

/*
Creates an HTTP request for the specified URL request object, and calls a handler upon completion.

request
An NSURLRequest object that provides the URL, cache policy, request type, body data or body stream, and so on.

completionHandler
The completion handler to call when the load request is complete. This handler is executed on the delegate queue.
Unless you have provided a custom delegate, this parameter must not be nil, because there is no other way to retrieve the response data.
*/

- (NSURLSessionDataTask *)dataTaskWithRequest:(NSURLRequest *)request 
completionHandler:(void (^)(NSData * __nullable data, NSURLResponse * __nullable response, NSError * __nullable error))completionHandler;

/*
Creates an HTTP GET request for the specified URL, then calls a handler upon completion.

url
The http or https URL to be retrieved.

completionHandler
The completion handler to call when the load request is complete. 
If sent to a session created by calling sessionWithConfiguration:delegate:delegateQueue: with a non-nil value for the delegateQueue parameter, 
this handler is executed on that delegate queue.
Unless you have provided a custom delegate, this parameter must not be nil, because there is no other way to retrieve the response data.
*/

- (NSURLSessionDataTask *)dataTaskWithURL:(NSURL *)url 
completionHandler:(void (^)(NSData * __nullable data, NSURLResponse * __nullable response, NSError * __nullable error))completionHandler;

/*
Creates a download task for the specified URL request, saves the results to a file, and calls a handler upon completion.

request
An NSURLRequest object that provides the URL, cache policy, request type, body data or body stream, and so on.

completionHandler
The completion handler to call when the load request is complete. This handler is executed on the delegate queue.
Unless you have provided a custom delegate, this parameter must not be nil, because there is no other way to retrieve the response data.
*/

- (NSURLSessionDownloadTask *)downloadTaskWithRequest:(NSURLRequest *)request 
completionHandler:(void (^)(NSURL * __nullable location, NSURLResponse * __nullable response, NSError * __nullable error))completionHandler;

/*
Creates a download task for the specified URL, saves the results to a file, and calls a handler upon completion.

url
An NSURL object that provides the URL to download.

completionHandler
The completion handler to call when the load request is complete. This handler is executed on the delegate queue.
Unless you have provided a custom delegate, this parameter must not be nil, because there is no other way to retrieve the response data.
*/

- (NSURLSessionDownloadTask *)downloadTaskWithURL:(NSURL *)url 
completionHandler:(void (^)(NSURL * __nullable location, NSURLResponse * __nullable response, NSError * __nullable error))completionHandler;

/*
Creates a download task to resume a previously canceled or failed download and calls a handler upon completion.

resumeData
A data object that provides the data necessary to resume the download.

completionHandler
The completion handler to call when the load request is complete. This handler is executed on the delegate queue.
Unless you have provided a custom delegate, this parameter must not be nil, because there is no other way to retrieve the response data.
*/

- (NSURLSessionDownloadTask *)downloadTaskWithResumeData:(NSData *)resumeData 
completionHandler:(void (^)(NSURL * __nullable location, NSURLResponse * __nullable response, NSError * __nullable error))completionHandler;



上面这些被创建的NSURLSessionTask对象,处于暂停状态,必须向其发送resume消息才能执行。





你可能感兴趣的:(网络请求,NSURLSession,Object_C)