简体   繁体   English

Swift 编写一个带有返回值的 async/await 方法

[英]Swift write an async/await method with return value

I want to write an async-await method with a return value, but my code doesn't work.我想编写一个带有返回值的 async-await 方法,但我的代码不起作用。 I also tried another way such as DispatchQueue.global DispatchGroup() and so on.我还尝试了另一种方式,例如DispatchQueue.global DispatchGroup()等。
Here is my code:这是我的代码:

func checkPassCode() -> Bool {

        var result = false

        let closure = { (_ flag:Bool) -> Void in
            result = flag
        }

        if var pin = self.keychain.get("pin") {
            let userPin = self.pin.joined(separator: "")
            let encryptedData = NSData(base64Encoded: pin, options: [])

            AsymmetricCryptoManager.sharedInstance.decryptMessageWithPrivateKey(encryptedData! as Data) { (success, result, error) -> Void in
                if success {
                    pin = result!
                    print("userPin is: \(userPin)")
                    print("storePin is: \(pin)")
                    closure(userPin == pin)
                } else {
                    print("Error decoding base64 string: \(String(describing: error))")
                    closure(false)
                }
            }
        }
        return result
    }

Thanks, vadian comment.谢谢,瓦迪安评论。 I used a closure as an input parameter of the method.我使用了一个闭包作为该方法的输入参数。

// MARK: - PassCode Methods
func checkPassCode(completionHandler:@escaping (_ flag:Bool) -> ()) {
    let storePin = getStorePin()
    let userPin = self.pin.joined(separator: "")
    AsymmetricCryptoManager.sharedInstance.decryptMessageWithPrivateKey(storePin as Data) { (success, result, error) -> Void in
        if success {
            let pin = result!
            print("userPin is: \(userPin)")
            print("storePin is: \(pin)")
            completionHandler(userPin == pin)
        } else {
            print("Error decoding base64 string: \(String(describing: error))")
            completionHandler(false)
        }
    }
}

func getStorePin() -> NSData {
    if let pin = self.keychain.get("pin") {
        return NSData(base64Encoded: pin, options: []) ?? NSData()
    }
    return NSData()
}

and then call this method:然后调用这个方法:

checkPassCode { success in
                    if success {
                        print("sucess")
                    } else {
                        print("not sucess!")
                    }
                }

You can use this framework for Swift coroutines - https://github.com/belozierov/SwiftCoroutine您可以将此框架用于 Swift 协程 - https://github.com/belozierov/SwiftCoroutine

When you call await it doesn't block the thread but only suspends coroutine, so you can use it in the main thread as well.当您调用 await 它不会阻塞线程而只会挂起协程,因此您也可以在主线程中使用它。

func awaitCheckPassCode() throws -> Bool {
    let storePin = getStorePin()
    let userPin = self.pin.joined(separator: "")
    let manager = AsymmetricCryptoManager.sharedInstance
    let (success, result, _) = try Coroutine.await {
        manager.decryptMessageWithPrivateKey(storePin as Data, completion: $0)
    }
    return success && userPin == result
}

and then call this method inside coroutine:然后在协程中调用这个方法:

DispatchQueue.main.startCoroutine {
    let success = try awaitCheckPassCode()

    if success {
        print("sucess")
    } else {
        print("not sucess!")
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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