【问题标题】:AlamoFire downloadProgress completion handler to async/awaitAlamoFire downloadProgress 完成处理程序到异步/等待
【发布时间】:2022-01-21 07:45:39
【问题描述】:

我创建了一个使用 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)")
    }
}

我将不胜感激。

【问题讨论】:

    标签: swift alamofire alamofire5


    【解决方案1】:

    您可以继续使用现有的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,否则当服务器未返回进度可用于totalUnitCountContent-Length 标头时,您将无法获得合理的值.

    【讨论】:

    • 我目前在我的 UI 中使用 progress.fractionCompleted 作为进度条,如果它有时不可靠,有什么替代方法?
    • 在这些情况下让您的 UI 切换到不确定的进度指示器。
    猜你喜欢
    • 1970-01-01
    • 2019-05-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-03
    • 2016-12-22
    相关资源
    最近更新 更多