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

How to use passcode lock scene in my app?

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

到目前为止我的代码:

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
        }
    }

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

喜欢下图:

我该怎么做?

此时,恐怕您无法将此密码锁屏访问到您的应用程序中,这与iOS本身有关。您可能需要构建自己的自定义视图控制器以 look/behave 作为密码锁定场景(使用 Touch ID)。我建议使用一个库来实现这一点,就我个人而言,我已经尝试过 PasscodeLock,它对我来说效果很好。

您应该使用 .deviceOwnerAuthentication 而不是 .deviceOwnerAuthenticationWithBiometrics 来评估政策。使用此参数,系统将使用生物识别身份验证(如果可用),否则它会显示密码屏幕。如果生物识别身份验证可用但失败,则后备按钮会重定向到密码屏幕。见 documentation :

If Touch ID or Face ID is available, enrolled, and not disabled, the user is asked for that first. Otherwise, they are asked to enter the device passcode.

Tapping the fallback button switches the authentication method to ask the user for the device 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.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")
        }
    }