后台下载
var task:URLSessionDownloadTask?
var session:URLSession?
if task != nil { return }
guard let url = URL(string: "http://dldir1.qq.com/qqfile/QQforMac/QQ_V5.5.1.dmg") else { return }
let request = URLRequest(url: url)
let config = URLSessionConfiguration.background(withIdentifier: "com.test.backgroundownload")
session = URLSession(configuration: config, delegate: self, delegateQueue: nil)
task = session?.downloadTask(with: request)
task?.resume()
- URLSessionDownloadDelegate
func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didWriteData bytesWritten: Int64, totalBytesWritten: Int64, totalBytesExpectedToWrite: Int64) {
if downloadTask == task {
let progress = Float(totalBytesWritten) / Float(totalBytesExpectedToWrite)
debugPrint("下载进度 \(progress)")
}
}
func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didResumeAtOffset fileOffset: Int64, expectedTotalBytes: Int64) {
let downloadedData = Float(fileOffset) / Float(expectedTotalBytes)
debugPrint("恢复下载 \(downloadedData)")
}
func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) {
debugPrint(#function)
if error == nil { return }
debugPrint(error?.localizedDescription ?? "")
}
func urlSessionDidFinishEvents(forBackgroundURLSession session: URLSession) {
DispatchQueue.main.async {
guard let appDelegate = UIApplication.shared.delegate as? AppDelegate else { return }
guard let completionHandler = appDelegate.completionHandler else { return }
completionHandler()
}
}