一奶栖、URL Session的基本概念
1.三種工作模式:
默認(rèn)會(huì)話模式(default):工作模式類似于原來(lái)的NSURLConnection,使用的是基于磁盤緩存的持久化策略彬碱,使用用戶keychain中保存的證書(shū)進(jìn)行認(rèn)證授權(quán)。
瞬時(shí)會(huì)話模式(ephemeral):該模式不使用磁盤保存任何數(shù)據(jù)。所有和會(huì)話相關(guān)的caches棋嘲,證書(shū)店溢,cookies等都被保存在RAM中叁熔,因此當(dāng)程序使會(huì)話無(wú)效,這些緩存的數(shù)據(jù)就會(huì)被自動(dòng)清空床牧。
后臺(tái)會(huì)話模式(background):該模式在后臺(tái)完成上傳和下載荣回,在創(chuàng)建Configuration對(duì)象的時(shí)候需要提供一個(gè)NSString類型的ID用于標(biāo)識(shí)完成工作的后臺(tái)會(huì)話。
2.NSURLSession支持的三種任務(wù)
NSURLSession類支持三種類型的任務(wù):加載數(shù)據(jù)戈咳,下載和上傳心软。
二、相關(guān)的類
NSURLConnection這個(gè)名字著蛙,實(shí)際上指的是一組構(gòu)成Foundation框架中URL加載系統(tǒng)的相互關(guān)聯(lián)的組件:NSURLRequest删铃,NSURLResponse,NSURLProtocol踏堡,NSURLCache猎唁,NSHTTPCookieStorage,NSURLCredentialStorage暂吉,以及和它同名的NSURLConnection胖秒。
在WWDC 2013中,Apple的團(tuán)隊(duì)對(duì)NSURLConnection進(jìn)行了重構(gòu)慕的,并推出了NSURLSession作為替代阎肝。
NSURLSession也是一組相互依賴的類,它的大部分組件和NSURLConnection中的組件相同如NSURLRequest肮街,NSURLCache等风题。而NSURLSession的不同之處在于,它將NSURLConnection替換為NSURLSession和NSURLSessionConfiguration嫉父,以及3個(gè)NSURLSessionTask的子類:NSURLSessionDataTask, NSURLSessionUploadTask, 和NSURLSessionDownloadTask沛硅。
下面來(lái)說(shuō)下NSURLSession新推出的類:
1.NSURLSessionConfiguration類
其中NSURLSessionConfiguration用于配置會(huì)話的屬性,可以通過(guò)該類配置會(huì)話的工作模式:
+ (NSURLSessionConfiguration *)defaultSessionConfiguration;??
+ (NSURLSessionConfiguration *)ephemeralSessionConfiguration;??
+ (NSURLSessionConfiguration *)backgroundSessionConfiguration:(NSString *)identifier; ?
在backgroundSessionConfiguration:方法中的identifier參數(shù)指定了會(huì)話的ID绕辖,用于標(biāo)記后臺(tái)的session摇肌。
該類的其中兩個(gè)屬性:
/* allow request to route over cellular. */?
?@property BOOL allowsCellularAccess;? ?
?/* allows background tasks to be scheduled at the discretion of the system for optimal performance. */?
?@property (getter=isDiscretionary) BOOL discretionary NS_AVAILABLE(NA, 7_0); ?
allowsCellularAccess 屬性指定是否允許使用蜂窩連接, discretionary屬性為YES時(shí)表示當(dāng)程序在后臺(tái)運(yùn)作時(shí)由系統(tǒng)自己選擇最佳的網(wǎng)絡(luò)連接配置仪际,該屬性可以節(jié)省通過(guò)蜂窩連接的帶寬围小。在使用后臺(tái)傳輸數(shù)據(jù)的時(shí)候昵骤,建議使用discretionary屬性,而不是allowsCellularAccess屬性肯适,因?yàn)樗鼤?huì)把WiFi和電源可用性考慮在內(nèi)变秦。補(bǔ)充:這個(gè)標(biāo)志允許系統(tǒng)為分配任務(wù)進(jìn)行性能優(yōu)化。這意味著只有當(dāng)設(shè)備有足夠電量時(shí)框舔,設(shè)備才通過(guò)Wifi進(jìn)行數(shù)據(jù)傳輸蹦玫。如果電量低,或者只僅有一個(gè)蜂窩連接刘绣,傳輸任務(wù)是不會(huì)運(yùn)行的樱溉。后臺(tái)傳輸總是在discretionary模式下運(yùn)行。
2.NSURLSession類
獲取NSURLSession類對(duì)象有幾種方式:
/*? * The shared session uses the currently set global NSURLCache,? * NSHTTPCookieStorage and NSURLCredentialStorage objects.? */?
?+ (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.??
* 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:(id)delegate delegateQueue:(NSOperationQueue *)queue;?
第一種方式是使用靜態(tài)的sharedSession方法额港,該類使用共享的會(huì)話饺窿,該會(huì)話使用全局的Cache,Cookie和證書(shū)移斩。
第二種方式是通過(guò)sessionWithConfiguration:方法創(chuàng)建對(duì)象肚医,也就是創(chuàng)建對(duì)應(yīng)配置的會(huì)話,與NSURLSessionConfiguration合作使用向瓷。
第三種方式是通過(guò)sessionWithConfiguration:delegate:delegateQueue方法創(chuàng)建對(duì)象肠套,二三兩種方式可以創(chuàng)建一個(gè)新會(huì)話并定制其會(huì)話類型。該方式中指定了session的委托和委托所處的隊(duì)列猖任。當(dāng)不再需要連接時(shí)你稚,可以調(diào)用Session的invalidateAndCancel直接關(guān)閉,或者調(diào)用finishTasksAndInvalidate等待當(dāng)前Task結(jié)束后關(guān)閉朱躺。這時(shí)Delegate會(huì)收到URLSession:didBecomeInvalidWithError:這個(gè)事件刁赖。Delegate收到這個(gè)事件之后會(huì)被解引用。
3.NSURLSessionTask類
NSURLSessionTask是一個(gè)抽象子類长搀,它有三個(gè)子類:NSURLSessionDataTask宇弛,NSURLSessionUploadTask和NSURLSessionDownloadTask。這三個(gè)類封裝了現(xiàn)代應(yīng)用程序的三個(gè)基本網(wǎng)絡(luò)任務(wù):獲取數(shù)據(jù)源请,比如JSON或XML枪芒,以及上傳和下載文件。
下面是其繼承關(guān)系:
有多種方法創(chuàng)建對(duì)應(yīng)的任務(wù)對(duì)象:
(1)NSURLSessionDataTask通過(guò)request對(duì)象或url創(chuàng)建:
/* 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;?
通過(guò)request對(duì)象或url創(chuàng)建谁尸,同時(shí)指定任務(wù)完成后通過(guò)completionHandler指定回調(diào)的代碼塊:
/*? * 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 *data, NSURLResponse *response, NSError *error))completionHandler;
- (NSURLSessionDataTask *)dataTaskWithURL:(NSURL *)url completionHandler:(void (^)(NSData *data, NSURLResponse *response, NSError *error))completionHandler;
(2)NSURLSessionUploadTask
通過(guò)request創(chuàng)建舅踪,在上傳時(shí)指定文件源或數(shù)據(jù)源。
/* 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;
在創(chuàng)建upload task對(duì)象時(shí)良蛮,通過(guò)completionHandler指定任務(wù)完成后的回調(diào)代碼塊:
/*
* upload convenience method.
*/
- (NSURLSessionUploadTask *)uploadTaskWithRequest:(NSURLRequest *)request fromFile:(NSURL *)fileURL completionHandler:(void (^)(NSData *data, NSURLResponse *response, NSError *error))completionHandler;
- (NSURLSessionUploadTask *)uploadTaskWithRequest:(NSURLRequest *)request fromData:(NSData *)bodyData completionHandler:(void (^)(NSData *data, NSURLResponse *response, NSError *error))completionHandler;
(3)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;
下載任務(wù)支持?jǐn)帱c(diǎn)續(xù)傳抽碌,第三種方式是通過(guò)之前已經(jīng)下載的數(shù)據(jù)來(lái)創(chuàng)建下載任務(wù)。
同樣地可以通過(guò)completionHandler指定任務(wù)完成后的回調(diào)代碼塊:
/*
* 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 *location, NSURLResponse *response, NSError *error))completionHandler;
- (NSURLSessionDownloadTask *)downloadTaskWithURL:(NSURL *)url completionHandler:(void (^)(NSURL *location, NSURLResponse *response, NSError *error))completionHandler;
- (NSURLSessionDownloadTask *)downloadTaskWithResumeData:(NSData *)resumeData completionHandler:(void (^)(NSURL *location, NSURLResponse *response, NSError *error))completionHandler;
4.NSURLSessionDelegate和NSURLSessionTaskDelegate協(xié)議
在協(xié)議的方法中可以完成各種各樣的回調(diào)動(dòng)作决瞳,如身份驗(yàn)證货徙、完成任務(wù)后的動(dòng)作泽裳、錯(cuò)誤處理和后臺(tái)任務(wù)完成的動(dòng)作等。委托方法指定在NSURLSession中一定數(shù)量的字節(jié)傳輸使用int64_t類型的參數(shù)破婆。
這里只說(shuō)下后臺(tái)任務(wù)的一個(gè)委托方法:
/* If an application has received an
* -application:handleEventsForBackgroundURLSession:completionHandler:
* message, the session delegate will receive this message to indicate
* that all messages previously enqueued for this session have been
* delivered.? At this time it is safe to invoke the previously stored
* completion handler, or to begin any internal updates that will
* result in invoking the completion handler.
*/
- (void)URLSessionDidFinishEventsForBackgroundURLSession:(NSURLSession *)session NS_AVAILABLE_IOS(7_0);
配合使用的ApplicationDelegate方法:
// Applications using an NSURLSession with a background configuration may be launched or resumed in the background in order to handle the
// completion of tasks in that session, or to handle authentication. This method will be called with the identifier of the session needing
// attention. Once a session has been created from a configuration object with that identifier, the session's delegate will begin receiving
// callbacks. If such a session has already been created (if the app is being resumed, for instance), then the delegate will start receiving
// callbacks without any action by the application. You should call the completionHandler as soon as you're finished handling the callbacks.
- (void)application:(UIApplication *)application handleEventsForBackgroundURLSession:(NSString *)identifier completionHandler:(void (^)())completionHandler NS_AVAILABLE_IOS(7_0);
將任務(wù)切換到后臺(tái)之后,Session的Delegate不會(huì)再收到和Task相關(guān)的消息胸囱。當(dāng)所有Task全都完成后祷舀,程序?qū)⒈粏拘眩⒄{(diào)用ApplicationDelegate的application:handleEventsForBackgroundURLSession:completionHandler:回調(diào)烹笔,在這里要為后臺(tái)session(由background session的identifier標(biāo)識(shí))指定對(duì)應(yīng)的回調(diào)代碼塊裳扯。
隨后,對(duì)于每一個(gè)完成的后臺(tái)Task調(diào)用該Session的Delegate中的URLSession:downloadTask:didFinishDownloadingToURL:(成功的話)和URLSession:task:didCompleteWithError:(成功或者失敗都會(huì)調(diào)用)方法做處理谤职,以上的回調(diào)代碼塊可以在這里調(diào)用饰豺。