简体   繁体   English

AlamoFire downloadProgress 完成处理程序到异步/等待

[英]AlamoFire downloadProgress completion handler to async/await

I have created a download handler which uses the downloadProgress and response completion handlers, but I want to convert this to Swift 5.5's new async/await syntax since AlamoFire released a version which supports swift concurrency.我创建了一个使用 downloadProgress 和响应完成处理程序的下载处理程序,但我想将其转换为 Swift 5.5 的新异步/等待语法,因为 AlamoFire 发布了支持 swift 并发的版本。

Here's my current code using completion handlers这是我当前使用完成处理程序的代码

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

Here's my attempt to convert to async/await syntax, but I am not sure how to implement downloadProgress这是我尝试转换为 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)")
    }
}

I would appreciate any help.我将不胜感激任何帮助。

You can continue using your existing downloadProgress handler, there's no requirement to switch to the new syntax, especially since doing so will look very similar.您可以继续使用现有的downloadProgress处理程序,无需切换到新语法,尤其是因为这样做看起来非常相似。

let task = AF.download("https://speed.hetzner.de/1GB.bin", to: destination)
  .downloadProgress { progress in
    print(progress.fractionCompleted)
  }
  .serializingDownloadedFileURL()

Or you can get the Progress stream and await the values in a separate Task .或者您可以获取Progress stream 并在单独的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()

Also, you shouldn't use progress.fractionCompleted unless the process.totalUnitCount > 0 , otherwise you won't get a reasonable value when the server doesn't return a Content-Length header that the progress can use for the totalUnitCount .此外,除非process.totalUnitCount > 0否则不应使用progress.fractionCompleted ,否则当服务器未返回进度可用于totalUnitCountContent-Length header 时,您将无法获得合理的值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM