文章摘录
var task:URLSessionDownloadTask?
var session:URLSession?
var resumeData:Data?
if resumeData == nil {
guard let url = URL(string: "http://dldir1.qq.com/qqfile/QQforMac/QQ_V5.5.1.dmg") else { return }
let request = URLRequest(url: url)
session = URLSession(configuration: URLSessionConfiguration.default, delegate: self, delegateQueue: nil)
task = session?.downloadTask(with: request)
} else {
guard let resumeData = resumeData else { return }
task = session?.downloadTask(withResumeData: resumeData)
}
task?.resume()
task?.cancel(byProducingResumeData: {[weak self](data) in
self?.resumeData = data
self?.task = nil
})
if task != nil {
task?.cancel()
task = nil
}
- URLSessionDownloadDelegate
func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didFinishDownloadingTo location: URL) {
let locationPath = location.path
let fileName = downloadTask.response?.suggestedFilename ?? ""
guard locationPath != "", fileName != "" else { return }
let documentsPath = NSHomeDirectory() + "/Library/Caches/Download"
let filePath = documentsPath + "/" + fileName
do {
if FileManager.default.fileExists(atPath: documentsPath) == false {
try FileManager.default.createDirectory(atPath: documentsPath, withIntermediateDirectories: true)
}
try FileManager.default.moveItem(atPath: locationPath, toPath: filePath)
} catch let catchError {
debugPrint("保存出错 = \(catchError.localizedDescription)")
}
}
func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didWriteData bytesWritten: Int64, totalBytesWritten: Int64, totalBytesExpectedToWrite: Int64) {
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)")
}