URLSession(二)简单的下载

690 阅读1分钟

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)")
    }
}

/*
 * 下载过程中写入数据会一直调用这个方法
 * didWriteData:之前已经下载完的数据量
 * bytesWritten:本次写入的数据量
 * totalBytesWritten:目前总共写入的数据量
 * totalBytesExpectedToWrite:文件总数据量
 */
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("恢复下载")
}