Search code examples
alamofireswift-concurrency

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?


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