【问题标题】:Face ID evaluation process not working properly面容 ID 评估流程无法正常工作
【发布时间】:2019-02-05 03:50:57
【问题描述】:

我正在尝试获取 Face ID 或 Touch ID 在下面的功能中是否成功

func authenticate() -> Bool{

    let context = LAContext()
    var error: NSError?

    guard context.canEvaluatePolicy(.deviceOwnerAuthenticationWithBiometrics, error: &error) else {
        return false
    }
    var returnValue = false
    let reason = "Face ID authentication"
    context.evaluatePolicy(.deviceOwnerAuthenticationWithBiometrics, localizedReason: reason) 
    {
        isAuthorized, error in
        guard isAuthorized == true else {
            return print(error)
        }
        returnValue = true
        print("success")
    }
    return returnValue        
}

但即使它成功使用此代码,它也会跳过稍后传递的returnValue = true,这会导致错误返回。 为什么会这样?以及如何修复此代码以使其按预期工作?

以上代码来自this link 以防万一这个人在看,谢谢。

【问题讨论】:

  • 您的代码非常好,准备好后执行错误处理。现在你有一个逻辑错误,你在实际执行异步任务时尝试返回。在最后一个 return 语句和evaluatePolicy 中设置一个断点。您将自己了解退货失败的原因。
  • 感谢回复,我试试看,多看懂代码。

标签: ios swift authentication touch-id face-id


【解决方案1】:

您应该使用闭包来获得评估结果。请注意,canEvaluatePolicy 的返回值是 Bool,但 evaluatePolicy 没有返回值,因为它接受闭包。

您可以修改方法以包含闭包而不是返回。

func authenticate(completion: ((Bool) -> ())) {
    ...
    completion(true) // false if it failed.
    ...
}

在您的应用程序的其他部分,您之前使用了返回值,您现在必须使用如下的闭包:

class Foo {
   func test() {
       let isEvaluated = self.authenticate() // Old way
       self.authenticate { success in
           // bool will now indicate whether evaluation was done successfully or not.
       }
   }
}

【讨论】:

  • 那么,我该怎么做才能解决这个问题?
  • 不要使用返回。使用这里提到的闭包。
【解决方案2】:

Touch ID & Face ID LocalAuthentication 的工作代码

(swift 4.0 & 5.0+ Code)

注意:Privacy - Face ID Usage Description 在 Info.plist 中添加键

使用

self.Authenticate { (success) in
     print(success)
}

本地认证功能

func Authenticate(completion: @escaping ((Bool) -> ())){
    
    //Create a context
    let authenticationContext = LAContext()
    var error:NSError?
    
    //Check if device have Biometric sensor
    let isValidSensor : Bool = authenticationContext.canEvaluatePolicy(.deviceOwnerAuthenticationWithBiometrics, error: &error)
    
    if isValidSensor {
        //Device have BiometricSensor
        //It Supports TouchID
        
        authenticationContext.evaluatePolicy(
            .deviceOwnerAuthenticationWithBiometrics,
            localizedReason: "Touch / Face ID authentication",
            reply: { [unowned self] (success, error) -> Void in
                
                if(success) {
                    // Touch / Face ID recognized success here
                    completion(true)
                } else {
                    //If not recognized then
                    if let error = error {
                        let strMessage = self.errorMessage(errorCode: error._code)
                        if strMessage != ""{
                            self.showAlertWithTitle(title: "Error", message: strMessage)
                        }
                    }
                    completion(false)
                }
        })
    } else {
        
        let strMessage = self.errorMessage(errorCode: (error?._code)!)
        if strMessage != ""{
            self.showAlertWithTitle(title: "Error", message: strMessage)
        }
    }
    
}

用消息处理错误代码

//MARK: TouchID error
func errorMessage(errorCode:Int) -> String{
    
    var strMessage = ""
    
    switch errorCode {
        
    case LAError.Code.authenticationFailed.rawValue:
        strMessage = "Authentication Failed"
        
    case LAError.Code.userCancel.rawValue:
        strMessage = "User Cancel"
        
    case LAError.Code.systemCancel.rawValue:
        strMessage = "System Cancel"
        
    case LAError.Code.passcodeNotSet.rawValue:
        strMessage = "Please goto the Settings & Turn On Passcode"
        
    case LAError.Code.touchIDNotAvailable.rawValue:
        strMessage = "TouchI or FaceID DNot Available"
        
    case LAError.Code.touchIDNotEnrolled.rawValue:
        strMessage = "TouchID or FaceID Not Enrolled"
        
    case LAError.Code.touchIDLockout.rawValue:
        strMessage = "TouchID or FaceID Lockout Please goto the Settings & Turn On Passcode"
        
    case LAError.Code.appCancel.rawValue:
        strMessage = "App Cancel"
        
    case LAError.Code.invalidContext.rawValue:
        strMessage = "Invalid Context"
        
    default:
        strMessage = ""
        
    }
    return strMessage
}

显示提示信息

//MARK: Show Alert
func showAlertWithTitle( title:String, message:String ) {
    let alert = UIAlertController(title: title, message: message, preferredStyle: .alert)
    
    let actionOk = UIAlertAction(title: "OK", style: .default, handler: nil)
    alert.addAction(actionOk)
    self.present(alert, animated: true, completion: nil)
}

【讨论】:

  • 在您的身份验证功能中,您能告诉我一种实现返回布尔值的方法吗?
  • @Yuto 检查我的更新答案以获取返回布尔值。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-04-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多