Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to do progress reporting using Async/Await swift?

I have a function that takes 2 callbacks. I want to convert this into async/await. But how can I await while continuously returning the progress also? I am using https://github.com/yannickl/AwaitKit to get rid of callbacks.

 typealias GetResultCallBack = (String) -> Void
 typealias ProgressCallBack = (Double) -> Void
   
 
func getFileFromS3(onComplete callBack: @escaping GetResultCallBack,
                  progress progressCallback: @escaping ProgressCallBack) {

}

I am using it like this:

getFileFromS3() { [weak self] (result) in
        guard let self = self else { return }
        
       // Do something with result
        
    } progress: { [weak self] (progress) in
        guard let self = self else { return }
        
        DispatchQueue.main.async { [weak self] in
            guard let self = self else {return}
            // Update progress in UI     
        }
        
    }

Here is what converted code looks without progress reporting:

func getFileFromS3() -> Promise<String> {  
  return async {

  //  return here
  }
}
like image 708
M Afham Avatar asked Mar 27 '26 04:03

M Afham


1 Answers

You could use a technique similar to this:

https://developer.apple.com/documentation/foundation/urlsession/3767352-data

As you can see from the signature...

func data(for request: URLRequest, 
          delegate: URLSessionTaskDelegate? = nil) async throws 
              -> (Data, URLResponse)

...it is async, but it also takes a delegate object:

https://developer.apple.com/documentation/foundation/urlsessiontaskdelegate

As you can see, that delegate receives callbacks for task progress. You can declare something similar, and thus feed that info from the delegate over to the main actor and the interface.

like image 180
matt Avatar answered Mar 28 '26 23:03

matt



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!