对上传请求使用 try await

Using try await with upload requests

我正在使用以下代码进行分段数据上传

let postValue = try await AF.upload(multipartFormData: { multipartFormData in
        multipartFormData.append("123".data(using: .utf8, allowLossyConversion: false)!, withName: "number1")
        multipartFormData.append("456".data(using: .utf8, allowLossyConversion: false)!, withName: "number2")
        multipartFormData.append("SomeLocation".data(using: .utf8, allowLossyConversion: false)!, withName: "location")
    }, to: "http://httpbin.org/post").uploadProgress { progress in
        debugPrint(progress)
    }.serializingDecodable(PostResponse.self).value

uploadProgress 在这种情况下用作闭包,这有点反对 try await。有没有更好的使用方法?

您可以使用 awaitable StreamOf<Progress>,但您需要单独处理异步流,因此继续使用闭包通常最方便 API .

let request = AF.upload(...)
Task {
  for await progress in request.uploadProgress() {
    debugPrint(progress)
  }
}
let value = try await request.serializingDecodable(PostResponse.self).value