URLSessionDownloadTask
Block方式下载,适合下载小文件,不需要监听下载进度
guard let url = URL(string: "https://ae01.alicdn.com/kf/Ue16c54cac6574a06a0c1afdad979b007W.jpg") else { return }
let request = URLRequest(url: url)
let session = URLSession.shared
let task = session.downloadTask(with: request) { location, response, error in
// location 是沙盒目录中临时路径,可能随时删除
let locationPath = location?.path ?? ""
let fileName = response?.suggestedFilename ?? ""
guard locationPath != "", fileName != "" else { return }
let documentsPath = NSHomeDirectory() + "/Library/Caches/com.image.cache"
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)")
}
}
task.resume()
代理方式下载
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.default
let session = URLSession(configuration: config, delegate: self, delegateQueue: nil)
let task = session.downloadTask(with: request)
task.resume()
- 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) {
debugPrint("恢复下载")
}