一.URLSesstion
- 基本用法
URLSession.shared.dataTask(with: url) { (data, response, error) in
if error == nil {
print("請求成功\(String(describing: response))" )
}
}.resume()
創(chuàng)建
session
會話對象
創(chuàng)建dataTask
網(wǎng)絡(luò)任務(wù)
開啟resume
任務(wù)
二. URLSessionConfiguration
1. 三種模式
open class URLSessionConfiguration : NSObject, NSCopying {
open class var `default`: URLSessionConfiguration { get }
open class var ephemeral: URLSessionConfiguration { get }
@available(iOS 8.0, *)
open class func background(withIdentifier identifier: String) -> URLSessionConfiguration
- 官方釋義
Default sessions behave much like the shared session (unless you customize them further), but let you obtain data incrementally using a delegate. You can create a default session configuration by calling the default method on the URLSessionConfiguration class.
Ephemeral sessions are similar to default sessions, but they don’t write caches, cookies, or credentials to disk. You can create an ephemeral session configuration by calling the ephemeral method on the URLSessionConfiguration class.
Background sessions let you perform uploads and downloads of content in the background while your app isn’t running. You can create a background session configuration by calling the backgroundSessionConfiguration(_:) method on the URLSessionConfiguration class.
default
是最常用的默認(rèn)模式庵楷,該模式下系統(tǒng)會創(chuàng)建一個持久化的緩存仔涩,同時將證書存儲在用戶的鑰匙串中ephemeral
除了沒有存儲外误趴,和default
差不多background
后臺運行模式虐译,可以使APP在沒運行的時候均澳,通過調(diào)用backgroundSessionConfiguration(_:)
,實現(xiàn)上傳和下載
- 下載任務(wù)示例:
let configuration = URLSessionConfiguration.background(withIdentifier: self.createID())
let session = URLSession.init(configuration: configuration, delegate: self, delegateQueue: OperationQueue.main)
session.downloadTask(with: url).resume()
- 下載任務(wù)主要由兩個代理方法,下載完成和下載進度
func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didFinishDownloadingTo location: URL) {
print("下載完成 - \(location)")
}
func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didWriteData bytesWritten: Int64, totalBytesWritten: Int64, totalBytesExpectedToWrite: Int64) {
print(" bytesWritten \(bytesWritten)\n totalBytesWritten \(totalBytesWritten)\n totalBytesExpectedToWrite \(totalBytesExpectedToWrite)")
print("下載進度: \(Double(totalBytesWritten)/Double(totalBytesExpectedToWrite))\n")
}
- 要想實現(xiàn)后臺下載,還需以下兩個步驟:
- 開啟后臺下載權(quán)限
//用于保存后臺下載的completionHandler var backgroundSessionCompletionHandler: (() -> Void)? func application(_ application: UIApplication, handleEventsForBackgroundURLSession identifier: String, completionHandler: @escaping () -> Void) { self.backgroundSessionCompletionHandler = completionHandler }
- 調(diào)用系統(tǒng)回調(diào)宴偿,更新屏幕
func urlSessionDidFinishEvents(forBackgroundURLSession session: URLSession) { print("后臺任務(wù)下載回來") DispatchQueue.main.async { guard let appDelegate = UIApplication.shared.delegate as? AppDelegate, let backgroundHandle = appDelegate.backgroundSessionCompletionHandler else { return } backgroundHandle() } }
2.常規(guī)屬性
identifier
:配置對象的后臺會話標(biāo)識符含长。httpAdditionalHeaders
:與請求一起發(fā)送的附加頭文件的字典。networkServiceType
:網(wǎng)絡(luò)服務(wù)的類型allowsCellularAccess
:布爾值畔规,是否允許蜂窩網(wǎng)絡(luò)連接局扶。timeoutIntervalForRequest
:等待其他數(shù)據(jù)時使用的超時間隔。timeoutIntervalForResource
:資源請求應(yīng)該允許的最大時間量叁扫。sharedContainerIdentifier
:應(yīng)該下載后臺URL會話中的文件的共享容器的標(biāo)識符详民。waitsForConnectivity
:一個布爾值,指示會話是否應(yīng)等待連接變?yōu)榭捎没蛘吡⒓词?/p>
3. 設(shè)置Cookie
政策
httpCookieAcceptPolicy
:決定何時應(yīng)該接受Cookie的策略常量httpShouldSetCookies
:一個布爾值陌兑,用于確定請求是否應(yīng)包含來自Cookie存儲的Cookie。httpCookieStorage
:管理cookie存儲的單一對象(共享實例)HTTPCookie
:表示HTTP cookie的對象由捎。它是一個不可變的對象兔综,從包含cookie屬性的字典中初始化
4. 設(shè)置安全策略
tlsMaximumSupportedProtocol
:在此會話中進行連接時客戶端應(yīng)請求的最大TLS協(xié)議版本。tlsMinimumSupportedProtocol
:協(xié)議協(xié)商期間應(yīng)該接受的最小TLS協(xié)議狞玛。urlCredentialStorage
:提供身份驗證憑據(jù)的憑證存儲
5. 設(shè)置緩存策略
urlCache
:用于向會話中的請求提供緩存響應(yīng)的URL緩存requestCachePolicy
:一個預(yù)定義常量软驰,用于確定何時從緩存中返回響應(yīng)
6. 支持后臺轉(zhuǎn)移
sessionSendsLaunchEvents
:一個布爾值,指示在傳輸完成時是否應(yīng)該在后臺繼續(xù)或啟動應(yīng)用程序isDiscretionary
:一個布爾值心肪,用于確定是否可以根據(jù)系統(tǒng)的判斷來調(diào)度后臺任務(wù)以獲得最佳性能锭亏。
7. 支持自定義協(xié)議
protocolClasses
:在會話中處理請求的額外協(xié)議子類的數(shù)組URLProtocol
:一個NSURLProtocol對象處理加載協(xié)議特定的URL數(shù)據(jù)。在NSURLProtocol類本身是一個抽象類硬鞍,可以為與特定URL方案的URL處理基礎(chǔ)設(shè)施慧瘤。您可以為您的應(yīng)用支持的任何自定義協(xié)議或URL方案創(chuàng)建子類
8. 支持多路徑TCP
multipathServiceType
:指定用于通過Wi-Fi和蜂窩接口傳輸數(shù)據(jù)的多路徑TCP連接策略的服務(wù)類型URLSessionConfiguration.MultipathServiceType
:指定多路徑TCP使用的服務(wù)類型的常量
9. 設(shè)置HTTP策略和代理屬性
httpMaximumConnectionsPerHost
:同時連接到給定主機的最大數(shù)量。httpShouldUsePipelining
:一個布爾值固该,用于確定會話是否應(yīng)使用HTTP流水線connectionProxyDictionary
:包含有關(guān)在此會話中使用的代理信息的字典
10. 支持連接變化
-
waitsForConnectivity
:一個布爾值锅减,指示會話是否應(yīng)等待連接變?yōu)榭捎没蛘吡⒓词 ?/li>
三.NSURLRequestCachePolicy
NSURLRequestUseProtocolCachePolicy = 0
: 默認(rèn)緩存策略
如果一個NSCachedURLResponse對于請求并不存在,數(shù)據(jù)將會從源端獲取伐坏。如果請求擁有一個緩存的響應(yīng)怔匣,那么URL加載系統(tǒng)會檢查這個響應(yīng)來決定,如果它指定內(nèi)容必須重新生效的話桦沉。假如內(nèi)容必須重新生效每瞒,將建立一個連向源端的連接來查看內(nèi)容是否發(fā)生變化金闽。假如內(nèi)容沒有變化,那么響應(yīng)就從本地緩存返回數(shù)據(jù)剿骨。如果內(nèi)容變化了代芜,那么數(shù)據(jù)將從源端獲取NSURLRequestReloadIgnoringLocalCacheData = 1
:URL應(yīng)該加載源端數(shù)據(jù),不使用本地緩存數(shù)據(jù)NSURLRequestReloadIgnoringLocalAndRemoteCacheData =4
:本地緩存數(shù)據(jù)懦砂、代理和其他中介都要忽視他們的緩存蜒犯,直接加載源數(shù)據(jù)
NSURLRequestReloadIgnoringCacheData = NSURLRequestReloadIgnoringLocalCacheDataNSURLRequestReturnCacheDataElseLoad = 2
:指定已存的緩存數(shù)據(jù)應(yīng)該用來響應(yīng)請求,不管它的生命時長和過期時間荞膘。如果在緩存中沒有已存數(shù)據(jù)來響應(yīng)請求的話罚随,數(shù)據(jù)從源端加載NSURLRequestReturnCacheDataDontLoad = 3
:指定已存的緩存數(shù)據(jù)用來滿足請求,不管生命時長和過期時間羽资。如果在緩存中沒有已存數(shù)據(jù)來響應(yīng)URL加載請求的話淘菩,不去嘗試從源段加載數(shù)據(jù),此時認(rèn)為加載請求失敗屠升。這個常量指定了一個類似于離線模式的行為NSURLRequestReloadRevalidatingCacheData = 5
:指定如果已存的緩存數(shù)據(jù)被提供它的源段確認(rèn)為有效則允許使用緩存數(shù)據(jù)響應(yīng)請求凝化,否則從源段加載數(shù)據(jù)。