Swift write an async/await method with return value

╄→гoц情女王★ 提交于 2021-01-29 17:52:58

问题


I want to write an async-await method with a return value, but my code doesn't work. I also tried another way such as DispatchQueue.global DispatchGroup() and so on.
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
    }

回答1:


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



回答2:


You can use this framework for Swift coroutines - 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.

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


来源:https://stackoverflow.com/questions/57935483/swift-write-an-async-await-method-with-return-value

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!