问题
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