利用URLSession實(shí)現(xiàn)后臺(tái)下載用法比較簡(jiǎn)單:
func backgroundDownloadTest(){
//url實(shí)例
let url: URL = URL.init(string: "http://pic1.win4000.com/pic/5/9e/4933293953.jpg")!
//會(huì)話配置
let config = URLSessionConfiguration.background(withIdentifier: "backgroundID")
//會(huì)話對(duì)象
let session = URLSession(configuration: config, delegate: self, delegateQueue: .main)
//啟動(dòng)會(huì)話
session.downloadTask(with: url).resume()
}
以上是初始化并啟動(dòng)會(huì)話的步驟尊勿。接下來需要在會(huì)話代理類中實(shí)現(xiàn)URLSessionDownloadDelegate中的方法:
urlSession(_:downloadTask:didFinishDownloadingTo:)
下載完成之后就回調(diào)
func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didFinishDownloadingTo location: URL) {
/*
下載完成 開始沙盒遷移
*/
print("下載完成--\(location.path)")
let locationPath = location.path
//拷貝到用戶目錄 文件名以時(shí)間戳命名
let documents = NSHomeDirectory()+"/Documents/" + self.getTimestampStr() + ".jpg"
print("遷移地址--\(documents)")
let fileManager = FileManager.default
try! fileManager.moveItem(atPath: locationPath, toPath: documents)
}
func getTimestampStr() -> String {
let date = NSDate()
let dateformatter = DateFormatter()
dateformatter.dateFormat = "yyyy年MM月dd日 HH:mm:ss"
print("當(dāng)前時(shí)間-\(dateformatter.string(from: date as Date))")
let timeInteval: TimeInterval = date.timeIntervalSince1970
let timeStamp = Int(timeInteval)
print("當(dāng)前時(shí)間時(shí)間戳-\(timeStamp)")
return String(timeStamp)
}
urlSession(_:downloadTask:didWriteData:totalBytesWritten:totalBytesExpectedToWrite:)
//下載進(jìn)度監(jiān)控
func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didWriteData bytesWritten: Int64, totalBytesWritten: Int64, totalBytesExpectedToWrite: Int64) {
print("bytesWritten \(bytesWritten), totalBytesWritten \(totalBytesWritten), totalBytesExpectedToWrite \(totalBytesExpectedToWrite)")
print("下載進(jìn)度:\(Double(totalBytesWritten)/Double(totalBytesExpectedToWrite))\n")
}
只是完成以上工作姻锁,還不能完成后臺(tái)下載任務(wù)紊册,還需要以下步驟:
AppDelegate中
//用于保存后臺(tái)下載的completionHandler
var backgroundSessionCompletionHandler: (() -> Void)?
func application(_ application: UIApplication, handleEventsForBackgroundURLSession identifier: String, completionHandler: @escaping () -> Void) {
self.backgroundSessionCompletionHandler = completionHandler
}
最后會(huì)話代理實(shí)現(xiàn):urlSessionDidFinishEvents(forBackgroundURLSession:)
// 告訴委托排隊(duì)等待會(huì)話的所有消息都已傳遞。 (Tells the delegate that all messages enqueued for a session have been delivered.)
func urlSessionDidFinishEvents(forBackgroundURLSession session: URLSession) {
print("后臺(tái)任務(wù)下載回來")
DispatchQueue.main.async {
guard let appDelegate = UIApplication.shared.delegate as? AppDelegate, let backgroundHandle = appDelegate.backgroundSessionCompletionHandler else { return }
backgroundHandle()
}
}
到此骨稿,后臺(tái)下載就可以順利完成了碉咆。