NSURLSession用法初探(一)

一奶栖、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)系:

繼承關(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)用饰豺。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個(gè)濱河市允蜈,隨后出現(xiàn)的幾起案子冤吨,更是在濱河造成了極大的恐慌,老刑警劉巖饶套,帶你破解...
    沈念sama閱讀 217,907評(píng)論 6 506
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件漩蟆,死亡現(xiàn)場(chǎng)離奇詭異,居然都是意外死亡妓蛮,警方通過(guò)查閱死者的電腦和手機(jī)怠李,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,987評(píng)論 3 395
  • 文/潘曉璐 我一進(jìn)店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來(lái)蛤克,“玉大人捺癞,你說(shuō)我怎么就攤上這事」辜罚” “怎么了髓介?”我有些...
    開(kāi)封第一講書(shū)人閱讀 164,298評(píng)論 0 354
  • 文/不壞的土叔 我叫張陵,是天一觀的道長(zhǎng)儿倒。 經(jīng)常有香客問(wèn)我版保,道長(zhǎng),這世上最難降的妖魔是什么夫否? 我笑而不...
    開(kāi)封第一講書(shū)人閱讀 58,586評(píng)論 1 293
  • 正文 為了忘掉前任彻犁,我火速辦了婚禮,結(jié)果婚禮上凰慈,老公的妹妹穿的比我還像新娘汞幢。我一直安慰自己,他們只是感情好微谓,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,633評(píng)論 6 392
  • 文/花漫 我一把揭開(kāi)白布森篷。 她就那樣靜靜地躺著输钩,像睡著了一般。 火紅的嫁衣襯著肌膚如雪仲智。 梳的紋絲不亂的頭發(fā)上买乃,一...
    開(kāi)封第一講書(shū)人閱讀 51,488評(píng)論 1 302
  • 那天,我揣著相機(jī)與錄音钓辆,去河邊找鬼剪验。 笑死,一個(gè)胖子當(dāng)著我的面吹牛前联,可吹牛的內(nèi)容都是我干的功戚。 我是一名探鬼主播,決...
    沈念sama閱讀 40,275評(píng)論 3 418
  • 文/蒼蘭香墨 我猛地睜開(kāi)眼似嗤,長(zhǎng)吁一口氣:“原來(lái)是場(chǎng)噩夢(mèng)啊……” “哼啸臀!你這毒婦竟也來(lái)了?” 一聲冷哼從身側(cè)響起烁落,我...
    開(kāi)封第一講書(shū)人閱讀 39,176評(píng)論 0 276
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤乘粒,失蹤者是張志新(化名)和其女友劉穎,沒(méi)想到半個(gè)月后顽馋,有當(dāng)?shù)厝嗽跇?shù)林里發(fā)現(xiàn)了一具尸體谓厘,經(jīng)...
    沈念sama閱讀 45,619評(píng)論 1 314
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,819評(píng)論 3 336
  • 正文 我和宋清朗相戀三年寸谜,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了竟稳。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點(diǎn)故事閱讀 39,932評(píng)論 1 348
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡熊痴,死狀恐怖他爸,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情果善,我是刑警寧澤诊笤,帶...
    沈念sama閱讀 35,655評(píng)論 5 346
  • 正文 年R本政府宣布,位于F島的核電站巾陕,受9級(jí)特大地震影響讨跟,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜鄙煤,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,265評(píng)論 3 329
  • 文/蒙蒙 一晾匠、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧梯刚,春花似錦凉馆、人聲如沸。這莊子的主人今日做“春日...
    開(kāi)封第一講書(shū)人閱讀 31,871評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)向叉。三九已至,卻和暖如春嗦董,著一層夾襖步出監(jiān)牢的瞬間母谎,已是汗流浹背。 一陣腳步聲響...
    開(kāi)封第一講書(shū)人閱讀 32,994評(píng)論 1 269
  • 我被黑心中介騙來(lái)泰國(guó)打工京革, 沒(méi)想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留销睁,地道東北人。 一個(gè)月前我還...
    沈念sama閱讀 48,095評(píng)論 3 370
  • 正文 我出身青樓存崖,卻偏偏與公主長(zhǎng)得像,于是被迫代替她去往敵國(guó)和親睡毒。 傳聞我的和親對(duì)象是個(gè)殘疾皇子来惧,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,884評(píng)論 2 354

推薦閱讀更多精彩內(nèi)容