【发布时间】:2015-10-19 14:02:34
【问题描述】:
最终,我想要的是一个函数(或者可能是一个单独的类中的函数),它提示用户通过 TouchID 进行身份验证,然后是密码,如果其中任何一个成功,则返回一个真正的布尔值。
我已经弄清楚了身份验证,但是我无法让函数返回布尔值,这大致是我目前所拥有的:
认证用户功能:
func authenticateUser() -> Bool {
let context = LAContext()
var error: NSError?
let reasonString = "Authentication is needed to access your places."
if context.canEvaluatePolicy(LAPolicy.DeviceOwnerAuthenticationWithBiometrics, error: &error) {
context.evaluatePolicy(LAPolicy.DeviceOwnerAuthenticationWithBiometrics, localizedReason: reasonString, reply: { (success, policyError) -> Void in
if success {
print("touchID authentication succesful")
} else {
switch policyError!.code {
case LAError.UserFallback.rawValue:
print("User selected to enter password.")
NSOperationQueue.mainQueue().addOperationWithBlock({ () -> Void in
self.showPasswordAlert()
})
default:
print("Authentication failed! :(")
}
}
})
} else {
print(error?.localizedDescription)
NSOperationQueue.mainQueue().addOperationWithBlock({ () -> Void in
self.showPasswordAlert()
})
}
return true
}
现在它只是设置为返回 true 用于测试目的。但是,只要身份验证成功,我希望它返回 true。我不能将返回值放在context.evaluatePolicy 中,因为它在块方法中。还有另一种方法可以做我想做的事吗?还是我以完全错误的方式处理这个问题?
另外,这里是我的showPasswordAlert函数供参考:
func showPasswordAlert() {
let alertController = UIAlertController(title: "Passcode", message: "Please enter your passcode.", preferredStyle: .Alert)
let defaultAction = UIAlertAction(title: "OK", style: .Default) { (action) -> Void in
if let textField = alertController.textFields?.first as UITextField? {
if let passcode = self.keychainWrapper.myObjectForKey("v_Data") as? String {
if textField.text == passcode {
print("Authentication successful! :) ")
} else {
}
}
}
}
let cancelAction = UIAlertAction(title: "Cancel", style: UIAlertActionStyle.Cancel, handler: nil)
alertController.addAction(defaultAction)
alertController.addAction(cancelAction)
alertController.addTextFieldWithConfigurationHandler { (textField) -> Void in
textField.placeholder = "Enter passcode..."
textField.textAlignment = NSTextAlignment.Center
textField.secureTextEntry = true
textField.keyboardType = UIKeyboardType.NumberPad
}
self.presentViewController(alertController, animated: true, completion: nil)
}
所以在我的脑海中,我的想法是:showPasswordAlert 也可以将一个真正的布尔值返回给authenticateUser,然后这又会返回一个真正的布尔值到 authenticateUser 函数被调用的位置。我知道有一种更简单的方法可以做到这一点,但我现在只想让它工作。
【问题讨论】:
-
相关排序:Throwing Exceptions in a Block Method 截至此评论,没有接受或正面评分的答案(其中 0 不是“正面”)
-
那么简短的回答是因为它在闭包内,所以不能按照我期望的方式完成?
-
不确定。也许有人会想出什么办法。
标签: ios swift authentication touch-id