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

标签 swift alamofire alamofire5

我创建了一个使用 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,否则当服务器不这样做时,您将无法获得合理的值返回进度可用于 totalUnitCountContent-Length header 。

关于swift - AlamoFire downloadProgress 完成处理程序异步/等待,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70409163/

相关文章:

ios - 删除以前添加的库时出现问题

ios - MKMapView 错误和 SFViewController 错误

java - 解析 withinMiles 首先返回最近的

ios - 如何在 Swift 中重新加载来自外部 API 的折线图数据?

即使配置了正确的后台模式,iOS 后台获取也无法正常工作

swift - alamofire swift : Can't download image to location specified by user

ios - 无法使用 Alamofire 方案构建工作区 Alamofire

swift - 获取分段上传 Alamofire5 的上传进度

ios - Alamofire 5 委托(delegate)中缺少 sessionDidReceiveChallenge

ios - Alamofire 5 替代 sessionDidReceiveChallenge