简体   繁体   中英

iOS Promise Kit and Await Kit in swift

I am trying to use async await / Promise. I have a function like this:

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)
        })
    }

}

Normally we call this function like this

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

}

So I want to remove this trailing closure implementation via AwaitKit ie want to replace via async await way.

How I do that so I can get the string? Something like

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

AwaitKit works in conjunction with PromiseKit to get the result you're waiting for. You'll need to change your function runWEC to return a Promise of a String like so:

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)
        })
    }
}

Then you'll be able to use the try? await() try? await() function.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM