一涉馁、URL Session的基本概念
1.三種工作模式:
默認(rèn)會(huì)話模式(default):工作模式類似于原來(lái)的NSURLConnection返咱,使用的是基于磁盤(pán)緩存的持久化策略,使用用戶keychain中保存的證書(shū)進(jìn)行認(rèn)證授權(quán)哥放。
瞬時(shí)會(huì)話模式(ephemeral):該模式不使用磁盤(pán)保存任何數(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. */
@propertyBOOL?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?*)configurationdelegate:(id?)delegatedelegateQueue:(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?*)requestcompletionHandler:(void?(^)(NSData?*data,NSURLResponse?*response,NSError?*error))completionHandler;
-?(NSURLSessionDataTask?*)dataTaskWithURL:(NSURL?*)urlcompletionHandler:(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?*)requestfromFile:(NSURL?*)fileURL;
/*?Creates?an?upload?task?with?the?given?request.??The?body?of?the?request?is?provided?from?the?bodyData.?*/
-?(NSURLSessionUploadTask?*)uploadTaskWithRequest:(NSURLRequest?*)requestfromData:(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?*)requestfromFile:(NSURL?*)fileURLcompletionHandler:(void?(^)(NSData?*data,NSURLResponse?*response,NSError?*error))completionHandler;
-?(NSURLSessionUploadTask?*)uploadTaskWithRequest:(NSURLRequest?*)requestfromData:(NSData?*)bodyDatacompletionHandler:(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?*)requestcompletionHandler:(void?(^)(NSURL?*location,NSURLResponse?*response,NSError?*error))completionHandler;
-?(NSURLSessionDownloadTask?*)downloadTaskWithURL:(NSURL?*)urlcompletionHandler:(void?(^)(NSURL?*location,NSURLResponse?*response,NSError?*error))completionHandler;
-?(NSURLSessionDownloadTask?*)downloadTaskWithResumeData:(NSData?*)resumeDatacompletionHandler:(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?*)applicationhandleEventsForBackgroundURLSession:(NSString?*)identifiercompletionHandler:(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)用咱圆。