如何使用 Async/Await 快速进行进度报告?

M A*_*ham 7 xcode async-await swift macos-big-sur

我有一个需要 2 个回调的函数。我想将其转换为异步/等待。但我怎样才能在等待的同时不断返回进度呢?我正在使用https://github.com/yannickl/AwaitKit来摆脱回调。

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

}
Run Code Online (Sandbox Code Playgroud)

我这样使用它:

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     
        }
        
    }
Run Code Online (Sandbox Code Playgroud)

以下是转换后的代码在没有进度报告的情况下的样子:

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

  //  return here
  }
}
Run Code Online (Sandbox Code Playgroud)

mat*_*att 7

您可以使用与此类似的技术:

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

从签名就可以看出...

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

...它是异步的,但它也需要一个委托对象:

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

正如您所看到的,该委托接收任务进度的回调。您可以声明类似的内容,从而将委托中的信息提供给主要参与者和界面。