網絡請求核心庫從iOS7之后已經從NSURLConnection換成了NSURLSession了。那么問題就來了,為什么要換,優點缺點是什么?帶著疑問開始追尋。先一張圖NSURLSession的框架
現在AFNetWorking的核心網絡請求邏輯就是使用這三個類。
NSURLConnection的缺點一:
直接先來一個蘋果文檔的解釋:
@discussion
The interface for NSURLConnection is very sparse, providing "only****" the controls to start and cancel asynchronous loads of a URL request.
蘋果在文檔中著重強調'only',不知道沒有出NSURLSession的時候有沒有only字眼。因為NSURLConnection只有start和cancel,那么cancel之后重新開始呢,你想對了只能重新開始。那問題來了,NSURLSession有什么牛逼之處呢?
NSURLSession優點
NSURLSession的三個方法如下:
- (void)suspend;
- (void)resume;
- (void)cancel;
NSURLConnection的缺點二:
NSURLConnection緩存的官方解釋:
- 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.
意思就是: NSURLConnection的資源數據在內存NSURLSession的資源數據一個在沙盒,顯然NSURLConnection更耗內存。
NSURLConnection的缺點三:
NSURLConnection進行斷點下載,通過設置訪問請求的HTTPHeaderField的Range屬性,開啟運行循環,NSURLConnection的代理方法作為運行循環的事件源,接收到下載數據時代理方法就會持續調用,并使用NSOutputStream管道流進行數據保存。
NSURLSession進行斷點下載,當暫停下載任務后,如果 downloadTask (下載任務)為非空,調用
cancelByProducingResumeData:(void (^)(NSData *resumeData))completionHandler
這個方法,這個方法接收一個參數,完成處理代碼塊,這個代碼塊有一個 NSData 參數 resumeData,如果 resumeData 非空,我們就保存這個對象到視圖控制器的 resumeData 屬性中。在點擊再次下載時,
通過調用
[ [self.session downloadTaskWithResumeData:self.resumeData]resume]
方法進行繼續下載操作。經過以上比較可以發現,使用NSURLSession進行斷點下載更加便捷。
NSURLConnection的缺點四:
NSURLSession的構造方法(sessionWithConfiguration:delegate:delegateQueue)中有一個 NSURLSessionConfiguration類的參數可以設置配置信息,其決定了cookie,安全和高速緩存策略,最大主機連接數,資源管理,網絡超時等配置。NSURLConnection不能進行這個配置,相比于 NSURLConnection 依賴于一個全局的配置對象,缺乏靈活性而言,NSURLSession 有很大的改進了。
NSURLSession可以設置三種配置信息,分別通過調用三個累方法返回配置對象:
(NSURLSessionConfiguration *)defaultSessionConfiguration,配置信息使用基于硬盤的持久話Cache,保存用戶的證書到鑰匙串,使用共享cookie存儲;
(NSURLSessionConfiguration *)ephemeralSessionConfiguration ,配置信息和default大致相同。除了,不會把cache,證書,或者任何和Session相關的數據存儲到硬盤,而是存儲在內存中,生命周期和Session一致。比如瀏覽器無痕瀏覽等功能就可以基于這個來做;
(NSURLSessionConfiguration *)backgroundSessionConfigurationWithIdentifier:(NSString *)identifier,配置信息可以創建一個可以在后臺甚至APP已經關閉的時候仍然在傳輸數據的session。注意,后臺Session一定要在創建的時候賦予一個唯一的identifier,這樣在APP下次運行的時候,能夠根據identifier來進行相關的區分。如果用戶關閉了APP,IOS 系統會關閉所有的background Session。而且,被用戶強制關閉了以后,IOS系統不會主動喚醒APP,只有用戶下次啟動了APP,數據傳輸才會繼續。