我創建了一個使用 downloadProgress 和回應完成處理程式的下載處理程式,但我想將其轉換為 Swift 5.5 的新 async/await 語法,因為 AlamoFire 發布了一個支持 swift 并發的版本。
這是我當前使用完成處理程式的代碼
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)")
}
}
我將不勝感激任何幫助。
uj5u.com熱心網友回復:
您可以繼續使用現有的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()
此外,progress.fractionCompleted除非process.totalUnitCount > 0,否則不應使用,否則當服務器未回傳Content-Length進度可用于totalUnitCount.
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/386662.html
