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

标签 ios swift asynchronous async-await dispatch

我想编写一个带有返回值的异步等待方法,但我的代码不起作用。我还尝试了另一种方式例如DispatchQueue.global DispatchGroup()等。
这是我的代码:

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
    }

最佳答案

谢谢,vadian评论。我使用闭包作为该方法的输入参数。

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

然后调用这个方法:

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

关于ios - Swift 编写一个带有返回值的 async/await 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57935483/

相关文章:

ios - 在 Swift 中使用闭包作为唯一参数初始化对象

asynchronous - Slack API方法发送 "typing"

ios - 垂直分段控制iOS

IOS DBAccess迁移到新的表结构

ios - 使用 "Pause"和 "Resume"功能从服务器下载数据

iphone - 添加/重新加载 map View 注释而不阻塞主线程

python - google app engine——异步代码块? Python

ios - iOS 应用程序中 NSURLConnection 的使用是否有限制?

swift - 每次加载 View 时都会触发UserDefaults.didChangeNotification

swift - 如果在文本字段中写入 200 我想在标签中打印 ok