系统后台下载
config三种模式
default
ephemeral
本文主角background
使用
分片下载
// 1:初始化configuration
let configuration = URLSessionConfiguration.background(withIdentifier:id)
// 2:初始化网络下载会话
let session = URLSession.init(configuration: configuration, delegate: self, delegateQueue: OperationQueue.main)
// 3:启动任务
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) {
// 下载进度
}
官方提示,需要在适当的时候调用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
}
}
最后实现代理
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) {
//实现调用
DispatchQueue.main.async {
guard let appDelegate = UIApplication.shared.delegate as? AppDelegate, let backgroundHandle = appDelegate.backgroundSessionCompletionHandler else { return }
backgroundHandle()
}
}
}
- 代码分散
- 不易于管理
- 不实现代理会使界面刷新卡顿
Warning: Application delegate received call to - application:handleEventsForBackgroundURLSession:completionHandler: but the completion handler was never called.
Alamofire下载
- 创建单例管理config
- 所有delegate内部封装
- 所有操作内部管理做好主线程callBack不需要外界操作
- 链式调用
- 不用在乎调用顺序
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
//下载回调信息
}
.downloadProgress { (progress) in
//下载进度
}
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
设置了一些基本的 SessionManager.defaultHTTPHeaders 请求头信息,上文提到的session的三种模式等
delegate
SessionDelegate 是集合所有的代理,所有事件统一处理
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,所以会回到系统的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) {
//实现调用
}
}
注意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
负责管理“ServerTrustPolicy”对象到给定主机的映射
待补充