如何在我的应用中使用密码锁定场景?

2 authentication xcode ios swift passcode

实际上,我构建了一个包含本地身份验证的应用程序。

到目前为止我的代码:

func authenticateUser() {
        let authenticationContext = LAContext()
        var error: NSError?
        let reasonString = "Touch the Touch ID sensor to unlock."

        // Check if the device can evaluate the policy.
        if authenticationContext.canEvaluatePolicy(LAPolicy.deviceOwnerAuthenticationWithBiometrics, error: &error) {

            authenticationContext.evaluatePolicy( .deviceOwnerAuthenticationWithBiometrics, localizedReason: reasonString, reply: { (success, evalPolicyError) in

                if success {
                    print("success")
                } else {
                    if let evaluateError = error as NSError? {
                        // enter password using system UI 
                    }

                }
            })

        } else {
            print("toch id not available")
           // enter password using system UI
        }
    }
Run Code Online (Sandbox Code Playgroud)

我的问题是当应用程序没有触摸 ID 或无效指纹时,我想使用密码锁定场景。

如下图:

在此处输入图片说明

我该怎么做?

小智 8

您应该使用.deviceOwnerAuthentication而不是.deviceOwnerAuthenticationWithBiometrics来评估策略。如果可用,系统将使用此参数使用生物识别身份验证,否则它会显示密码屏幕。如果生物识别身份验证可用但失败,回退按钮将重定向到密码屏幕。请参阅文档

如果 Touch ID 或 Face ID 可用、已注册且未禁用,则首先要求用户提供。否则,他们会被要求输入设备密码。

点击回退按钮可切换身份验证方法以询问用户设备密码。

所以你的代码将是:

func authenticateUser() {
        let authenticationContext = LAContext()
        var error: NSError?
        let reasonString = "Touch the Touch ID sensor to unlock."

        // Check if the device can evaluate the policy.
        if authenticationContext.canEvaluatePolicy(LAPolicy.deviceOwnerAuthentication, error: &error) {

            authenticationContext.evaluatePolicy( .deviceOwnerAuthentication, localizedReason: reasonString, reply: { (success, evalPolicyError) in

                if success {
                    print("success")
                } else {
                    // Handle evaluation failure or cancel
                }
            })

        } else {
            print("passcode not set")
        }
    }
Run Code Online (Sandbox Code Playgroud)