系統(tǒng)后臺下載
config三種模式
default
ephemeral
本文主角background使用
分片下載
// 1:初始化configuration
let configuration = URLSessionConfiguration.background(withIdentifier:id)
// 2:初始化網(wǎng)絡(luò)下載會話
let session = URLSession.init(configuration: configuration, delegate: self, delegateQueue: OperationQueue.main)
// 3:啟動任務(wù)
session.downloadTask(with: url).resume()
//MARK: - session代理
extension ViewController:URLSessionDownloadDelegate{
func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didFinishDownloadingTo location: URL) {
// 下載完成
}
func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didWriteData bytesWritten: Int64, totalBytesWritten: Int64, totalBytesExpectedToWrite: Int64) {
// 下載進(jìn)度
}
官方提示,需要在適當(dāng)?shù)臅r候調(diào)用handler
You should call the completionHandler as soon as you're finished handling the callbacks.
So
//用于保存后臺下載的completionHandler
var backgroundSessionCompletionHandler: (() -> Void)?
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
//用于保存后臺下載的completionHandler
var backgroundSessionCompletionHandler: (() -> Void)?
func application(_ application: UIApplication, handleEventsForBackgroundURLSession identifier: String, completionHandler: @escaping () -> Void) {
self.backgroundSessionCompletionHandler = completionHandler
}
}
最后實現(xiàn)代理
extension ViewController:URLSessionDownloadDelegate{
func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didFinishDownloadingTo location: URL) {
}
func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didWriteData bytesWritten: Int64, totalBytesWritten: Int64, totalBytesExpectedToWrite: Int64) {}
func urlSessionDidFinishEvents(forBackgroundURLSession session: URLSession) {
//實現(xiàn)調(diào)用
DispatchQueue.main.async {
guard let appDelegate = UIApplication.shared.delegate as? AppDelegate, let backgroundHandle = appDelegate.backgroundSessionCompletionHandler else { return }
backgroundHandle()
}
}
}
- 代碼分散
- 不易于管理
- 不實現(xiàn)代理會使界面刷新卡頓
Warning: Application delegate received call to - application:handleEventsForBackgroundURLSession:completionHandler: but the completion handler was never called.
Alamofire下載
- 創(chuàng)建單例管理config
- 所有delegate內(nèi)部封裝
- 所有操作內(nèi)部管理做好主線程callBack不需要外界操作
- 鏈?zhǔn)秸{(diào)用
- 不用在乎調(diào)用順序
struct XXBackgroundManger {
static let shared = XXBackgroundManger()
let manager: SessionManager = {
let configuration = URLSessionConfiguration.background(withIdentifier: "xxxx.demo")
configuration.httpAdditionalHeaders = SessionManager.defaultHTTPHeaders
return SessionManager(configuration: configuration)
}()
}
func application(_ application: UIApplication, handleEventsForBackgroundURLSession identifier: String, completionHandler: @escaping () -> Void) {
XXBackgroundManger.shared.manager.backgroundCompletionHandler = completionHandler
}
XXBackgroundManger.shared.manager
.download(self.urlDownloadStr) { (url, response) -> (destinationURL: URL, options: DownloadRequest.DownloadOptions) in
//下載完成
}
.response { (downloadResponse) in
//下載回調(diào)信息
}
.downloadProgress { (progress) in
//下載進(jìn)度
}
SessionManger流程分析
SessionManager.swift
public init(
configuration: URLSessionConfiguration = URLSessionConfiguration.default,
delegate: SessionDelegate = SessionDelegate(),
serverTrustPolicyManager: ServerTrustPolicyManager? = nil)
{
self.delegate = delegate
self.session = URLSession(configuration: configuration, delegate: delegate, delegateQueue: nil)
commonInit(serverTrustPolicyManager: serverTrustPolicyManager)
}
SessionManger初始化
- configuration
- delegate
- serverTrustPolicyManager
configuration
設(shè)置了一些基本的 SessionManager.defaultHTTPHeaders 請求頭信息,上文提到的session的三種模式等
delegate
SessionDelegate 是集合所有的代理,所有事件統(tǒng)一處理

代理集合.png
SessionManager.swift
在我們初始化manager的時候,會在commonInit()方法中
public init(
configuration: URLSessionConfiguration = URLSessionConfiguration.default,
delegate: SessionDelegate = SessionDelegate(),
serverTrustPolicyManager: ServerTrustPolicyManager? = nil)
{
·
·
commonInit(serverTrustPolicyManager: serverTrustPolicyManager)
}
private func commonInit(serverTrustPolicyManager: ServerTrustPolicyManager?) {
session.serverTrustPolicyManager = serverTrustPolicyManager
delegate.sessionManager = self
delegate.sessionDidFinishEventsForBackgroundURLSession = { [weak self] session in
guard let strongSelf = self else { return }
DispatchQueue.main.async { strongSelf.backgroundCompletionHandler?() }
}
}
因為前邊保存了delegate,所以會回到系統(tǒng)的delegate
extension ViewController:URLSessionDownloadDelegate{
func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didFinishDownloadingTo location: URL) {}
func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didWriteData bytesWritten: Int64, totalBytesWritten: Int64, totalBytesExpectedToWrite: Int64) {}
func urlSessionDidFinishEvents(forBackgroundURLSession session: URLSession) {
//實現(xiàn)調(diào)用
}
}
注意urlSessionDidFinishEvents,因為SessionDelegate重寫的方法,
#if !os(macOS)
/// Tells the delegate that all messages enqueued for a session have been delivered.
///
/// - parameter session: The session that no longer has any outstanding requests.
open func urlSessionDidFinishEvents(forBackgroundURLSession session: URLSession) {
sessionDidFinishEventsForBackgroundURLSession?(session)
}
#endif
會回到
SessionDelegate.swift
delegate.sessionDidFinishEventsForBackgroundURLSession = { [weak self] session in
guard let strongSelf = self else { return }
DispatchQueue.main.async { strongSelf.backgroundCompletionHandler?() }
}
完成主線程的毀掉
serverTrustPolicyManager
/// Responsible for managing the mapping of ServerTrustPolicy objects to a given host
負(fù)責(zé)管理“ServerTrustPolicy”對象到給定主機(jī)的映射
待補(bǔ)充