【问题标题】:iOS Promise Kit and Await Kit in swiftswift中的iOS Promise Kit和Await Kit
【发布时间】:2020-09-28 22:37:47
【问题描述】:

我正在尝试使用异步等待/承诺。我有这样的功能:

extension DemoWebCrypto {

    class func runWEC(password: String, encrypted: Data) {
        let crypto = WebCrypto()
        crypto.decrypt(data: encrypted,
                       password: password,
                       callback: { (decrypted: Data?, error: Error?) in
              print("Error:", error)
              let text = String(data: decrypted!, encoding: .utf8)
              print("decrypt:", text)
        })
    }

}

通常我们这样称呼这个函数

let enc1 = "......."
let password = "....."
let data1 = Data(base64Encoded: enc1, options: .ignoreUnknownCharacters)!
DemoWebCrypto.runEC(password: password, encrypted: data1) {

}

所以我想通过 AwaitKit 删除这个尾随闭包实现,即想通过异步等待方式替换。

我怎么做才能得到字符串?像

let result = try await(DemoWebCrypto.runWEC(password: ..., encrypted: ...))
print(result) // the decrypt text

【问题讨论】:

    标签: ios swift promise async-await promisekit


    【解决方案1】:

    AwaitKit 与 PromiseKit 一起工作以获得您正在等待的结果。您需要更改您的函数 runWEC 以返回 PromiseString ,如下所示:

    class func runWEC(password: String, encrypted: Data) -> Promise<String> {
        return Promise { seal in
            let crypto = WebCrypto()
            crypto.decrypt(data: encrypted,
                           password: password,
                           callback: { (decrypted: Data?, error: Error?) in
                  if let error = error {
                      seal.reject(error)
                  }
    
                  let text = String(data: decrypted!, encoding: .utf8)
                  seal.fulfill(text)
            })
        }
    }
    

    然后你就可以使用try? await()函数了。

    if let result = try? await(DemoWebCrypto.runWEC(password: ..., encrypted: ...)) {
        print(result) // the decrypt text
    }
    

    【讨论】:

      猜你喜欢
      • 2016-10-20
      • 2021-09-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多