我试图根据touch id的成功/失败返回true或false。但是当调用条件成功时,函数将以false值退出。我是iOS开发的新手。我相信我应该使用某种完成处理程序,但在这种特殊情况下我不明白该怎么做。
func authenticateUser(reasonString: String) -> Bool {
// Get the local authentication context.
let context = LAContext()
// Declare a NSError variable.
var error: NSError?
// Current authorization status of user
var isAuthorized = false
// Check if the device can evaluate the policy.
if context.canEvaluatePolicy(LAPolicy.DeviceOwnerAuthenticationWithBiometrics, error: &error) {
[context .evaluatePolicy(LAPolicy.DeviceOwnerAuthenticationWithBiometrics, localizedReason: reasonString, reply: { (success: Bool, evalPolicyError: NSError?) -> Void in
if success {
isAuthorized = true
}
else{
// If authentication failed then show a message to the console with a short description.
// In case that the error is a user fallback, then show the password alert view.
print(evalPolicyError?.localizedDescription)
switch evalPolicyError!.code {
case LAError.SystemCancel.rawValue:
print("Authentication was cancelled by the system")
case LAError.UserCancel.rawValue:
print("Authentication was cancelled by the user")
case LAError.UserFallback.rawValue:
print("User selected to enter custom password")
default:
print("Authentication failed")
}
}
})]
}
else{
// If the security policy cannot be evaluated then show a short message depending on the error.
switch error!.code{
case LAError.TouchIDNotEnrolled.rawValue:
print("TouchID is not enrolled")
case LAError.PasscodeNotSet.rawValue:
print("A passcode has not been set")
default:
// The LAError.TouchIDNotAvailable case.
print("TouchID not available")
}
// Optionally the error description can be displayed on the console.
print(error?.localizedDescription)
}
return isAuthorized
}
即使在执行touchID部分之前,此函数也会返回false。有人可以指导吗?
答案 0 :(得分:0)
您的函数authenticateUser将始终返回false,因为您返回isAuthorized值,设置为ti false。 context.canEvaluatePolicy和context.evaluatePolicy仍在执行,并且isAuthorized的值不会更改。
实际流量有点像这样:
设置isAuthorized == false
{call context.canEvaluatePolicy - >还在执行 call context.evaluatePolicy - >关于context.canEvaluatePolicy}
的成功Return isAuthorized = False - > context.canEvaluatePolicy和context.evaluatePolicy仍在执行。
执行流程完成方法执行,即使正在执行块方法。
我的建议是从函数末尾删除return isAuthorized并实现成功和失败块。