URLSession(四) 后台下载

333 阅读1分钟
后台下载
var task:URLSessionDownloadTask? // 下载任务
var session:URLSession? // 下载session
  • 开始下载
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)
// 后台下载任务必须设置为background,并且 Identifier 必须保证唯一
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()
    }
}