Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Using try await with upload requests

I am using the following code for multipart data upload

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

the uploadProgress is used as a closure in this case which is kind of against the try await. Is there a better way for using it?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

There is an awaitable StreamOf<Progress> you can use, but you’ll need to handle the async stream separately, so it’s often most convenient to keep using the closure API.

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

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading