NSURLSession简介和使用

NSURLSession

NSURLSession指的不仅仅是同名类NSURLSession,包括一系列的类。和NSURLConnection一样。包括NSURLRequest、NSURLResponse、NSURLProtocol、NSURLCache、NSHTTPCookieStorage、NSURLCredentialStorage、NSURLSession、NSURLSessionConfiguration以及NSURLSessionTask 的3个子类:NSURLSessionDataTask、NSURLSessionUploadTask、NSURLSessionDownloadTask

与 NSURLConnection 相比,NSURLsession 最直接的改进就是可以配置每个 session 的缓存,协议,cookie,以及证书策略(credential policy),甚至跨程序共享这些信息。这将允许程序和网络基础框架之间相互独立,不会发生干扰。每个 NSURLSession 对象都由一个 NSURLSessionConfiguration 对象来进行初始化,后者指定了刚才提到的那些策略以及一些用来增强移动设备上性能的新选项。

NSURLSessionTask 处理数据的加载以及文件和数据在客户端与服务器之间的上传和下载。

NSURLSessionTask 是一个父类,具体网络任务有三个子类完成,获取数据、上传文件和下载文件。NSURLSessionDataTask、NSURLSessionUploadTask、NSURLSessionDownloadTask。
当NSURLSessionDataTask完成时,会带来相关的数据

NS_CLASS_AVAILABLE(NSURLSESSION_AVAILABLE, 7_0)
@interface NSURLSession : NSObject
/* Creates a data task with the given request.  The request may have a body stream. */
- (NSURLSessionDataTask *)dataTaskWithRequest:(NSURLRequest *)request;

/* Creates a data task to retrieve the contents of the given URL. */
- (NSURLSessionDataTask *)dataTaskWithURL:(NSURL *)url;

/*
 * data task convenience methods.  These methods create tasks that
 * bypass the normal delegate calls for response and data delivery,
 * and provide a simple cancelable asynchronous interface to receiving
 * data.  Errors will be returned in the NSURLErrorDomain, 
 * see .  The delegate, if any, will still be
 * called for authentication challenges.
 */
- (NSURLSessionDataTask *)dataTaskWithRequest:(NSURLRequest *)request completionHandler:(void (^)(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error))completionHandler;
- (NSURLSessionDataTask *)dataTaskWithURL:(NSURL *)url completionHandler:(void (^)(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error))completionHandler;

NSURLSessionUploadTask 上传任务,一般上传任务服务端也会返回响应的数据,所以继承自NSURLSessionDataTask

/* Creates an upload task with the given request.  The body of the request will be created from the file referenced by fileURL */
- (NSURLSessionUploadTask *)uploadTaskWithRequest:(NSURLRequest *)request fromFile:(NSURL *)fileURL;

/* Creates an upload task with the given request.  The body of the request is provided from the bodyData. */
- (NSURLSessionUploadTask *)uploadTaskWithRequest:(NSURLRequest *)request fromData:(NSData *)bodyData;

/* Creates an upload task with the given request.  The previously set body stream of the request (if any) is ignored and the URLSession:task:needNewBodyStream: delegate will be called when the body payload is required. */
- (NSURLSessionUploadTask *)uploadTaskWithStreamedRequest:(NSURLRequest *)request;

/*
 * upload convenience method.
 */
- (NSURLSessionUploadTask *)uploadTaskWithRequest:(NSURLRequest *)request fromFile:(NSURL *)fileURL completionHandler:(void (^)(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error))completionHandler;
- (NSURLSessionUploadTask *)uploadTaskWithRequest:(NSURLRequest *)request fromData:(nullable NSData *)bodyData completionHandler:(void (^)(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error))completionHandler;

NSURLSessionDownloadTask 任务结束时,会带来已下载文件的一个临时文件路径。

/* Creates a download task with the given request. */
- (NSURLSessionDownloadTask *)downloadTaskWithRequest:(NSURLRequest *)request;

/* Creates a download task to download the contents of the given URL. */
- (NSURLSessionDownloadTask *)downloadTaskWithURL:(NSURL *)url;

/* Creates a download task with the resume data.  If the download cannot be successfully resumed, URLSession:task:didCompleteWithError: will be called. */
- (NSURLSessionDownloadTask *)downloadTaskWithResumeData:(NSData *)resumeData;

/*
 * download task convenience methods.  When a download successfully
 * completes, the NSURL will point to a file that must be read or
 * copied during the invocation of the completion routine.  The file
 * will be removed automatically.
 */
- (NSURLSessionDownloadTask *)downloadTaskWithRequest:(NSURLRequest *)request completionHandler:(void (^)(NSURL * _Nullable location, NSURLResponse * _Nullable response, NSError * _Nullable error))completionHandler;
- (NSURLSessionDownloadTask *)downloadTaskWithURL:(NSURL *)url completionHandler:(void (^)(NSURL * _Nullable location, NSURLResponse * _Nullable response, NSError * _Nullable error))completionHandler;
- (NSURLSessionDownloadTask *)downloadTaskWithResumeData:(NSData *)resumeData completionHandler:(void (^)(NSURL * _Nullable location, NSURLResponse * _Nullable response, NSError * _Nullable error))completionHandler;

Task类之间的关系如下:

NSURLSession简介和使用_第1张图片
NSURLSession.png

因为父类中NSURLSessionTask中有取消、暂停、恢复功能,所有Task都含有该动能。

NSURLSessionDownloadTask 取消时,可以通过选项来创建一个恢复数据,然后传递给下一次新创建的downloadTask,以便继续之前的下载。

/* Cancel the download (and calls the superclass -cancel).  If
 * conditions will allow for resuming the download in the future, the
 * callback will be called with an opaque data blob, which may be used
 * with -downloadTaskWithResumeData: to attempt to resume the download.
 * If resume data cannot be created, the completion handler will be
 * called with nil resumeData.
 */
- (void)cancelByProducingResumeData:(void (^)(NSData * _Nullable resumeData))completionHandler;

task 是由一个NSURLSession创建的,每个task的构造方法都对应有completionHandler和没有这Block版本。不带有block的版本如下:

/* 
 * NSURLSessionTask objects are always created in a suspended state and
 * must be sent the -resume message before they will execute.
 */

/* Creates a data task with the given request.  The request may have a body stream. */
- (NSURLSessionDataTask *)dataTaskWithRequest:(NSURLRequest *)request;

/* Creates a data task to retrieve the contents of the given URL. */
- (NSURLSessionDataTask *)dataTaskWithURL:(NSURL *)url;

/* Creates an upload task with the given request.  The body of the request will be created from the file referenced by fileURL */
- (NSURLSessionUploadTask *)uploadTaskWithRequest:(NSURLRequest *)request fromFile:(NSURL *)fileURL;

/* Creates an upload task with the given request.  The body of the request is provided from the bodyData. */
- (NSURLSessionUploadTask *)uploadTaskWithRequest:(NSURLRequest *)request fromData:(NSData *)bodyData;

/* Creates an upload task with the given request.  The previously set body stream of the request (if any) is ignored and the URLSession:task:needNewBodyStream: delegate will be called when the body payload is required. */
- (NSURLSessionUploadTask *)uploadTaskWithStreamedRequest:(NSURLRequest *)request;

/* Creates a download task with the given request. */
- (NSURLSessionDownloadTask *)downloadTaskWithRequest:(NSURLRequest *)request;

/* Creates a download task to download the contents of the given URL. */
- (NSURLSessionDownloadTask *)downloadTaskWithURL:(NSURL *)url;

/* Creates a download task with the resume data.  If the download cannot be successfully resumed, URLSession:task:didCompleteWithError: will be called. */
- (NSURLSessionDownloadTask *)downloadTaskWithResumeData:(NSData *)resumeData;

NSURLSession 与NSURLConnection的delegate方法可以通过改映射表进行查看(https://gist.github.com/floriankugler/6870499)

NSURLSessionConfiguration

该对象为主要用于NSURLSession对象进行初始化,对以前NSMutableRequest所提供的网络请求设置选项进行扩充,提供更大的灵活性和操控权。

/*
 * 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.
 * If you do specify a delegate, the delegate will be retained until after
 * the delegate has been sent the URLSession:didBecomeInvalidWithError: message.
 */
+ (NSURLSession *)sessionWithConfiguration:(NSURLSessionConfiguration *)configuration;
+ (NSURLSession *)sessionWithConfiguration:(NSURLSessionConfiguration *)configuration delegate:(nullable id )delegate delegateQueue:(nullable NSOperationQueue *)queue;

NSURLSession在初始化时会对配置的NSURLSessionConfiguration 进行一次拷贝,之后对Configuration进行修改也不会对NSURLSession有影响

/*
 * The shared session uses the global singleton credential, cache
 * and cookie storage objects.
 *
 * An ephemeral session has no persistent disk storage for cookies,
 * cache or credentials.
 *
 * A background session can be used to perform networking operations
 * on behalf of a suspended application, within certain constraints.
 */
NS_CLASS_AVAILABLE(NSURLSESSION_AVAILABLE, 7_0)
@interface NSURLSessionConfiguration : NSObject 

#if FOUNDATION_SWIFT_SDK_EPOCH_AT_LEAST(8)
@property (class, readonly, strong) NSURLSessionConfiguration *defaultSessionConfiguration;
@property (class, readonly, strong) NSURLSessionConfiguration *ephemeralSessionConfiguration;
#endif

+ (NSURLSessionConfiguration *)backgroundSessionConfigurationWithIdentifier:(NSString *)identifier NS_AVAILABLE(10_10, 8_0);

NSURLSessionConfiguration的三个工厂方法

1、defaultSessionConfiguration 返回标准的configuration,共享全局NSHTTPCookieStorage,NSURLCache 和 NSURLCredentialStorage

2、ephemeralSessionConfiguration 返回一个预设配置,不会对缓存、cookie、证书进行持久性存储。

3、+ (NSURLSessionConfiguration *)backgroundSessionConfigurationWithIdentifier:(NSString *)identifier NS_AVAILABLE(10_10, 8_0);
创建一个后台session,可以在应用挂起、退出或者崩溃的情况下运行上传和下载任务

@interface NSURLSessionConfiguration : NSObject 

/* 三种创建方式 */

+ (NSURLSessionConfiguration *)defaultSessionConfiguration;
+ (NSURLSessionConfiguration *)ephemeralSessionConfiguration;
+ (NSURLSessionConfiguration *)backgroundSessionConfigurationWithIdentifier:(NSString *)identifier NS_AVAILABLE(10_10, 8_0);

/* 当使用上述第三种方式创建后台sessionConfiguration时可以读到初始化时传入的唯一标识,其他创建方式都为空 */
@property (nullable, readonly, copy) NSString *identifier;

/* 
缓存策略,默认值是NSURLRequestUseProtocolCachePolicy
 */
@property NSURLRequestCachePolicy requestCachePolicy;

/* 给request指定每次接收数据超时间隔,如果下一次接受新数据用时超过该值,则发送一个请求超时给该request。默认为60s */
@property NSTimeInterval timeoutIntervalForRequest;

/* 给指定resource设定一个超时时间,resource需要在时间到达之前完成。默认是7天。 */
@property NSTimeInterval timeoutIntervalForResource;

/* 指定网络传输类型。精切指出传输类型,可以让系统快速响应,提高传输质量,延长电池寿命等。
typedef NS_ENUM(NSUInteger, NSURLRequestNetworkServiceType)
{
    NSURLNetworkServiceTypeDefault = 0,    // 普通网络传输,默认使用这个
    NSURLNetworkServiceTypeVoIP = 1,    // 网络语音通信传输,只能在VoIP使用
    NSURLNetworkServiceTypeVideo = 2,    // 影像传输
    NSURLNetworkServiceTypeBackground = 3, // 网络后台传输,优先级不高时可使用。对用户不需要的网络操作可使用
    NSURLNetworkServiceTypeVoice = 4       // 语音传输
};
 */
@property NSURLRequestNetworkServiceType networkServiceType;

/* 是否使用蜂窝网络,默认是yes. */
@property BOOL allowsCellularAccess;

/* 是否由系统根据性能自动裁量后台任务。默认值是NO。同sessionSendsLaunchEvent一样,只对后台configuration有效。 */
@property (getter=isDiscretionary) BOOL discretionary NS_AVAILABLE(10_10, 7_0);

/* 
如果要为app的插件提供session,需要给这个值赋值
 */
@property (nullable, copy) NSString *sharedContainerIdentifier NS_AVAILABLE(10_10, 8_0);

/* 
 表示当后台传输结束时,是否启动app.这个属性只对 后台sessionConfiguration 生效,其他configuration类型会自动忽略该值。默认值是YES。
 */
@property BOOL sessionSendsLaunchEvents NS_AVAILABLE(NA, 7_0);

/* 
指定了会话连接中的代理服务器。同样地,大多数面向消费者的应用程序都不需要代理,所以基本上不需要配置这个属性,默认为NULL
*/
@property (nullable, copy) NSDictionary *connectionProxyDictionary;

/* 确定是否支持SSLProtocol版本的会话
 */
@property SSLProtocol TLSMinimumSupportedProtocol;

/* 
确定是否支持SSLProtocol版本的会话
*/
@property SSLProtocol TLSMaximumSupportedProtocol;

/* 
它可以被用于开启HTTP管道,这可以显着降低请求的加载时间,但是由于没有被服务器广泛支持,默认是禁用的
 */
@property BOOL HTTPShouldUsePipelining;

/* 
默认为yes,是否提供来自shareCookieStorge的cookie,如果想要自己提供cookie,可以使用HTTPAdditionalHeaders来提供。
 */
@property BOOL HTTPShouldSetCookies;

/* Policy for accepting cookies.  This overrides the policy otherwise specified by the cookie storage. */
@property NSHTTPCookieAcceptPolicy HTTPCookieAcceptPolicy;

/* 
指定了一组默认的可以设置出站请求的数据头。这对于跨会话共享信息,如内容类型,语言,用户代理,身份认证,是很有用的。
例如:
    @{@"Accept": @"application/json",
     @"Accept-Language": @"en",
     @"Authorization": authString,
     @"User-Agent": userAgentString
   }
 */
@property (nullable, copy) NSDictionary *HTTPAdditionalHeaders;

/* 
同时连接一个host的最大数。iOS默认是4.APP是作为一个整体来看的
 */
@property NSInteger HTTPMaximumConnectionsPerHost;

/* 
存储cookie,清除存储,直接set为nil即可。
对于默认和后台的session,使用sharedHTTPCookieStorage。
对于短暂的session,cookie仅仅储存到内存,session失效时会自动清除。
 */
@property (nullable, retain) NSHTTPCookieStorage *HTTPCookieStorage;

/* 
证书存储,如果不使用,可set为nil.
默认和后台session,默认使用的sharedCredentialStorage.
短暂的session使用一个私有存储在内存中。session失效会自动清除。
 */
@property (nullable, retain) NSURLCredentialStorage *URLCredentialStorage;

/* 
缓存NSURLRequest的response。
默认的configuration,默认值的是sharedURLCache。
后台的configuration,默认值是nil
短暂的configuration,默认一个私有的cache于内存,session失效,cache自动清除。
*/
@property (nullable, retain) NSURLCache *URLCache;

/* Enable extended background idle mode for any tcp sockets created.    Enabling this mode asks the system to keep the socket open
 *  and delay reclaiming it when the process moves to the background (see https://developer.apple.com/library/ios/technotes/tn2277/_index.html) 
 */
@property BOOL shouldUseExtendedBackgroundIdleMode NS_AVAILABLE(10_11, 9_0);

/* 
处理NSURLRequest的NSURLProtocol的子类。
重要:对后台Session失效。
 */
@property (nullable, copy) NSArray *protocolClasses;

@end

NSURLSession 与NSURLConnection区别

普通任务和上传

NSURLSession对网络操作提供三个类进行分别的处理。
NSURLSessionDataTask 负责普通网络请求,NSURLSessionUploadTask负责上传,NSURLSessionDownloadTask负责下载任务。
当执行普通网络请求时,NSURLSessionDataTask 与NSURLConnection基本没有差别
上传任务时,NSURLSession与NSURLConnection需要设置POST请求的请求体上进行

下载任务

NSURLConnection下载文件时,先是将整个文件下载到内存,然后再写入到沙盒,如果文件比较大,就会出现内存暴涨的情况。
而使用NSURLSessionUploadTask下载文件,会默认下载到沙盒中,下载完成后会把tem中的临时文件删除,需要在初始化任务方法时,需要在completionHandler回调中增加保存文件。

请求方法的控制

NSURLConnection 具有start 和 cancel方法,cancel后,不能继续访问,只能重写创建新的请求。
NSURLSession有三个控制方法。取消(cancel)、暂停(suspend)、继续(resume),暂停以后可以通过继续恢复当前的请求任务。

断点续传

NSURLConnection进行断点续传,通过设置访问请求中的HTTPHeaderField的Range属性,开启进行循环,NSURLConnection的代理方法作为运行循环的事件源,接收到下载数据时代理方法就会持续调用,并使用NSOutputStream管道流进行数据保存。

NSURLSession进行断点续传,当Session被suspend时,会调用cancelByProducingResumeData:(void (^)(NSData *resumeData))completionHandler 改方法中的resumeData为已经下载的数据,可以保持下来,当点击再次下载时,可以执行[ [self.session downloadTaskWithResumeData:self.resumeData]resume] 方法,进行继续下载。

配置信息

NSURLSession通过NSURLSessionConfiguration类的参数设置配置信息,可以设置cookie,安全,缓存策略,最大主机连接数等。NSURLConnect配置信息依赖于全局对象,缺乏灵活性。

想要查看更多关于 session task 的信息,可以查看 WWDC Session 705: "What’s New in Foundation Networking"
想要查看更多关于后台 session 的信息,可以查看 WWDC Session 204: "What's New with Multitasking"

你可能感兴趣的:(NSURLSession简介和使用)