这次我们来讲一讲
Alamofire的后台下载,实际项目中,也有很多时候需要使用到后台下载的需求。
Alamofire提供的后台下载功能很好用,但是,我们在学习研究Alamofire框架的时候,也会遇到一些问题,接下来,我们就来探索一下。
苹果原生URLSession后台下载
使用方法
苹果原生URLSession处理后台下载非常简单:
// 1:初始化一个background的模式的configuration
let configuration = URLSessionConfiguration.background(withIdentifier: self.createID())
// 2:通过configuration初始化网络下载会话
let session = URLSession.init(configuration: configuration, delegate: self, delegateQueue: OperationQueue.main)
// 3:session创建downloadTask任务-resume启动
session.downloadTask(with: url).resume()
- 首先,我们初始化一个具有
background模式的URLSessionConfiguration,只有在该模式下,才能进行后台下载(在后面附录中会讲一下URLSessionConfiguration初始化的三种模式)。- 通过
configuration初始化网络下载会话session,设置相关代理,回调数据信号响应。- 然后,通过
session创建downloadTask任务,resume启动。
然后是网络的发起请求到数据请求成功后的回调处理:
extension ViewController:URLSessionDownloadDelegate{
func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didFinishDownloadingTo location: URL) {
// 下载完成 - 开始沙盒迁移
print("下载完成 - \(location)")
let locationPath = location.path
//拷贝到用户目录(文件名以时间戳命名)
let documnets = NSHomeDirectory() + "/Documents/" + self.lgCurrentDataTurnString() + ".mp4"
print("移动地址:\(documnets)")
//创建文件管理器
let fileManager = FileManager.default
try! fileManager.moveItem(atPath: locationPath, toPath: documnets)
}
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")
}
}
- 必要性,实现
URLSessionDownloadDelegate的didFinishDownloadingTo代理,实现下载完成转移临时文件里的数据到相应沙盒保存- 通过
urlSession(_ session: downloadTask:didWriteData bytesWritten: totalBytesWritten: totalBytesExpectedToWrite: )的代理监听下载进度
到此,咱们的下载功能也已经实现了,但是,需要后台下载,因此,我们还差一步骤:
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
//用于保存后台下载的completionHandler
var backgroundSessionCompletionHandler: (() -> Void)?
func application(_ application: UIApplication, handleEventsForBackgroundURLSession identifier: String, completionHandler: @escaping () -> Void) {
self.backgroundSessionCompletionHandler = completionHandler
}
}
- 我们只需要实现
handleEventsForBackgroundURLSession就可以完美后台下载- 应用程序在所有与
URLSession对象 关联的后台传输完成后调用此方法,无论传输成功完成还是导致错误。如果一个或多个传输需要认证,应用程序也会调用这个方法。- 使用此方法可以重新连接任何
URLSession并更新应用程序的用户界面。例如,您可以使用此方法更新进度指示器或将新内容合并到视图中。在处理事件之后,在completionHandler参数中执行block,这样应用程序就可以获取用户界面的刷新。
然后,我们需要实现在urlSessionDidFinishEvents的代理调用:
func urlSessionDidFinishEvents(forBackgroundURLSession session: URLSession) {
print("后台任务下载回来")
DispatchQueue.main.async {
guard let appDelegate = UIApplication.shared.delegate as? AppDelegate, let backgroundHandle = appDelegate.backgroundSessionCompletionHandler else { return }
backgroundHandle()
}
}
- 拿到UIApplication.shared.delegate的回调函数执行
- 注意线程切换主线程,因为我们需要刷新界面
注意: 如果不实现这个代理里面的回调函数的执行
- 后台下载的能力是不会影响
- 会爆出非常验证界面刷新卡顿,影响用户体验
- 同时打印台会爆出警告
Warning: Application delegate received call to -
application:handleEventsForBackgroundURLSession:completionHandler:
but the completion handler was never called.
附录
URLSessionConfiguration初始化的三种模式
default
default:默认模式,通常我们用这种模式就足够了。default模式下系统会创建一个持久化的缓存并在用户的钥匙串中存储证书。
ephemeral
ephemeral:系统没有任何持久性存储,所有内容的生命周期都与session相同,当session无效时,所有内容自动释放。
background
background:创建一个可以在后台甚至APP已经关闭的时候仍然在传输数据的会话。background模式与default模式非常相似,不过background模式会用一个独立线程来进行数据传输。background模式可以在程序挂起,退出,崩溃的情况下运行task。也可以利用标识符来恢复进。注意,后台Session一定要在创建的时候赋予一个唯一的identifier,这样在APP下次运行的时候,能够根据identifier来进行相关的区分。如果用户关闭了APP,IOS系统会关闭所有的background Session。而且,被用户强制关闭了以后,IOS系统不会主动唤醒APP,只有用户下次启动了APP,数据传输才会继续。
Alamofire后台下载
在上一篇文章Alamofire(二)-- Alamofire配置、以及数据请求中,我们已经学习了
Alamofire的常用方法还有Alamofire的一些特性,所以,我们接下来探索一下后台下载。
前奏分析
首先,我们先来看一段代码:
HSBackgroundManger.shared.manager
.download(self.urlDownloadStr) { (url, response) -> (destinationURL: URL, options: DownloadRequest.DownloadOptions) in
let documentUrl = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first
let fileUrl = documentUrl?.appendingPathComponent(response.suggestedFilename!)
return (fileUrl!,[.removePreviousFile,.createIntermediateDirectories])
}
.response { (downloadResponse) in
print("下载回调信息: \(downloadResponse)")
}
.downloadProgress { (progress) in
print("下载进度 : \(progress)")
}
在这里,我们封装了一个单例类
HSBackgroundManger,用于管理后台下载。
看看内部结构:
struct HSBackgroundManger {
static let shared = LGBackgroundManger()
let manager: SessionManager = {
let configuration = URLSessionConfiguration.background(withIdentifier: "com.hs.AlamofireTest.demo")
configuration.httpAdditionalHeaders = SessionManager.defaultHTTPHeaders
configuration.timeoutIntervalForRequest = 10
configuration.timeoutIntervalForResource = 10
configuration.sharedContainerIdentifier = "group.com.hs.AlamofireTest"
return SessionManager(configuration: configuration)
}()
}
那么到了这里,我们干嘛不直接使用URLSession,转而使用单例封装一个类?对比分析:
SessionManager.defalut是不能用于后台下载的需求的,session的配置应该选用background模式进行URLSessionConfiguration的设置。- 做成单例,也是为了全局持有,避免在进入后台的时候,被释放掉,从而导致网络报错:
Error Domain=NSURLErrorDomain Code=-999 "cancelled"。- 达到网络层与应用层的分离目的。
- 可以直接在
appdelegate更方便的回调接收
SessionManger的流程分析
SessionManger初始化
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)
}
- 首先,初始化
session,其中configuration是default的模式,设置了一些基本的SessionManager.defaultHTTPHeaders请求头信息。- 代理移交,通过创建
SessionDelegate这个专门处理代理的类来实现URLSession的代理。
代理回调
SessionDelegate的代理方法如下:
URLSessionDelegate
URLSessionTaskDelegate
URLSessionDataDelegate
URLSessionDownloadDelegate
URLSessionStreamDelegate
先看下urlSessionDidFinishEvents的代理方法:
open func urlSessionDidFinishEvents(forBackgroundURLSession session: URLSession) {
sessionDidFinishEventsForBackgroundURLSession?(session)
}
上面调用了 sessionDidFinishEventsForBackgroundURLSession闭包的执行,那么这个闭包在什么时候申明的呢?
delegate.sessionDidFinishEventsForBackgroundURLSession = { [weak self] session in
guard let strongSelf = self else { return }
DispatchQueue.main.async { strongSelf.backgroundCompletionHandler?() }
}
- 只要后台下载完成就会来到这个闭包内部。
- 回调了主线程,调用了
backgroundCompletionHandler, 这也是SessionManger对外提供的功能。
流程总结
- 首先在
AppDelegate的handleEventsForBackgroundURLSession方法里,把回调闭包传给了SessionManager的backgroundCompletionHandler- 在下载完成回来的时候
SessionDelegate的urlSessionDidFinishEvents代理的调用 ->sessionDidFinishEventsForBackgroundURLSession- 然后
sessionDidFinishEventsForBackgroundURLSession执行 ->SessionManager的backgroundCompletionHandler- 最后调用
AppDelegate的completionHandler
总结
不管你是使用URLSession的方式,还是 Alamofire 进行后台下载,原理还是一样的,只是 Alamofire 使用更加达到依赖下沉,网络层下沉,使用更简洁。
最后,在cooci老师的威逼下,感谢一下cooci老师文章Alamofire-后台下载。大家都去看看,很受用的啊。