我创建了一个使用 downloadProgress 和响应完成处理程序的下载处理程序,但我想将其转换为 Swift 5.5 的新 async/await 语法,因为 AlamoFire 发布了支持快速并发的版本。
这是我当前使用完成处理程序的代码
func startDownload() {
let destination = DownloadRequest.suggestedDownloadDestination(for: .documentDirectory)
AF.download("https://speed.hetzner.de/1GB.bin", to: destination)
.downloadProgress { progress in
print(progress.fractionCompleted)
}
.response { response in
print(response)
}
}
这是我尝试转换为 async/await 语法,但我不确定如何实现 downloadProgress
func startDownload() async {
let destination = DownloadRequest.suggestedDownloadDestination(for: .documentDirectory)
let downloadTask = AF.download("https://speed.hetzner.de/1GB.bin", to: destination).serializingDownloadedFileURL()
do {
let fileUrl = try await downloadTask.value
print(fileUrl)
} catch {
print("Download error! \(error.localizedDescription)")
}
}
如果有任何帮助,我将不胜感激。
最佳答案
您可以继续使用现有的 downloadProgress
处理程序,无需切换到新语法,特别是因为这样做看起来非常相似。
let task = AF.download("https://speed.hetzner.de/1GB.bin", to: destination)
.downloadProgress { progress in
print(progress.fractionCompleted)
}
.serializingDownloadedFileURL()
或者您可以获取 Progress
流并在单独的 Task
中等待值。
let request = AF.download("https://speed.hetzner.de/1GB.bin", to: destination)
Task {
for await progress in request.downloadProgress() {
print(progress)
}
}
let task = request.serializingDownloadedFileURL()
此外,除非 process.totalUnitCount > 0
,否则不应使用 progress.fractionCompleted
,否则当服务器不这样做时,您将无法获得合理的值返回进度可用于 totalUnitCount
的 Content-Length
header 。
关于swift - AlamoFire downloadProgress 完成处理程序异步/等待,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70409163/