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