NSURLSession和NSURLConnection

網絡請求核心庫從iOS7之後已經從NSURLConnection換成了NSURLSession了。那麼問題就來了,爲什麼要換,優點缺點是什麼?帶着疑問開始追尋。
先一張圖NSURLSession的框架。
NSURLSession的核心類框架圖
現在AFNetWorking的核心網絡請求邏輯就是使用這三個類。

  1. NSURLConnection的缺點

    • 缺點1

直接先來一個蘋果文檔的解釋。

@discussion

        The interface for NSURLConnection is very sparse, providing
        "only****" the controls to start and cancel asynchronous loads of a
        URL request.

蘋果在文檔中着重強調only,不知道沒有出NSURLSession的時候有沒有,我估計沒有(意淫)之前沒有主意解釋。因爲只有start和cancel,那麼cancel之後重新開始呢,你想對了只能重新開始。那問題來了,NSURLSession有什麼牛逼之處呢?
下邊是NSURLSessionTask文檔代碼:

/* -cancel returns immediately, but marks a task as being canceled.
 * The task will signal -URLSession:task:didCompleteWithError: with an
 * error value of { NSURLErrorDomain, NSURLErrorCancelled }.  In some 
 * cases, the task may signal other work before it acknowledges the 
 * cancelation.  -cancel may be sent to a task that has been suspended.
 */
- (void)cancel;
/*
 * Suspending a task will prevent the NSURLSession from continuing to
 * load data.  There may still be delegate calls made on behalf of
 * this task (for instance, to report data received while suspending)
 * but no further transmissions will be made on behalf of the task
 * until -resume is sent.  The timeout timer associated with the task
 * will be disabled while a task is suspended. -suspend and -resume are
 * nestable. 
 */
- (void)suspend;
- (void)resume;

來自:NSURLSession.h 

變爲3個方法:cancel,suspend,resume。意味着暫停之後還能繼續請求。是不是靈活很多。

  • 缺點2

    An NSURLConnection may be used for loading of resource data
    directly to memory, in which case an
    NSURLConnectionDataDelegate should be supplied, or for
    downloading of resource data directly to a file, in which case
    an NSURLConnectionDownloadDelegate is used. The delegate is
    retained by the NSURLConnection until a terminal condition is
    encountered. These two delegates are logically subclasses of
    the base protocol, NSURLConnectionDelegate.<p>

NSURLSession

 An NSURLSessionDownloadTask will directly write the response data to
 a temporary file.  When completed, the delegate is sent
 URLSession:downloadTask:didFinishDownloadingToURL: and given an opportunity 
 to move this file to a permanent location in its sandboxed container, or to
 otherwise read the file. If canceled, an NSURLSessionDownloadTask can
 produce a data blob that can be used to resume a download at a later
 time.

一個在內存一個在沙盒,顯然前者更耗內存。

  • 缺點3

    斷點續傳
    NSURLConnection進行斷點下載,通過設置訪問請求的HTTPHeaderField的Range屬性,開啓運行循環,NSURLConnection的代理方法作爲運行循環的事件源,接收到下載數據時代理方法就會持續調用,並使用NSOutputStream管道流進行數據保存。
    NSURLSession進行斷點下載,當暫停下載任務後,如果 downloadTask (下載任務)爲非空,調用 cancelByProducingResumeData:(void (^)(NSData *resumeData))completionHandler 這個方法,這個方法接收一個參數,完成處理代碼塊,這個代碼塊有一個 NSData 參數 resumeData,如果 resumeData 非空,我們就保存這個對象到視圖控制器的 resumeData 屬性中。在點擊再次下載時,通過調用 [ [self.session downloadTaskWithResumeData:self.resumeData]resume]方法進行繼續下載操作。
    經過以上比較可以發現,使用NSURLSession進行斷點下載更加便捷。

- (NSURLSessionDownloadTask *)downloadTaskWithResumeData:(NSData *)resumeData completionHandler:(void (^)(NSURL *location, NSURLResponse *response, NSError *error))completionHandler
Description 
Creates a download task to resume a previously canceled or failed download and calls a handler upon completion. The task bypasses calls to delegate methods for response and data delivery, and instead provides any resulting NSURL, NSURLResponse, and NSError objects inside the completion handler. Delegate methods for handling authentication challenges, however, are still called.
The new session download task.
Parameters  
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.
If you pass nil, only the session delegate methods are called when the task completes, making this method equivalent to the downloadTaskWithResumeData: method.
location
The location of a temporary file where the server’s response is stored. You must move this file or open it for reading before your completion handler returns. Otherwise, the file is deleted, and the data is lost.
response
An object that provides response metadata, such as HTTP headers and status code. If you are making an HTTP or HTTPS request, the returned object is actually an NSHTTPURLResponse object.
error
An error object that indicates why the request failed, or nil if the request was successful.

以後有新的研究繼續更新。有問題大家隨時評論,共同學習
參考思路:http://www.cnblogs.com/kakaluote123/articles/5426923.html

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章