有没有办法在iOS模拟器上使用苹果的Touch ID(指纹扫描仪)?

24

我正在开发一个需要Touch ID身份验证的应用程序,那么有没有办法在模拟器中使用Touch ID(指纹扫描仪)?

此外,请分享一些使用LocalAuthentication框架的示例代码。


如果您曾经阅读过这篇内容,请接受其他答案。 - arekolek
4个回答

64

XCODE 7 beta支持在iPhone模拟器中测试Touch ID身份验证功能。您可以尝试用于测试。

[截图1]

[截图1]

[截图2]

[截图2]


1
我们如何使用Selenium触发此操作? - es3735746
3
在UITest的XCTestCase的setUp方法中触发这个是否可能? - Josh Gafni
1
即使我已经启用了“Touch ID Enrolled”,但仍然会出现“使用密码支付”的提示,而不是指纹。有人知道可能是为什么吗? - Tri Nguyen

10

从Xcode 7起,模拟器支持'touchID'。下面的答案包含更多信息。

截至最新测试版(第6版),模拟器没有办法模拟指纹扫描。老实说,我怀疑即使在以后的测试版中也不会包含这个功能。

您需要在设备上进行测试。

要立即使用身份验证框架,您需要: * XCode 6 * 安装iOS 8的iPhone 5s

您需要执行以下步骤:

查找设备是否支持指纹验证以及是否已注册指纹:

@import LocalAuthentication;

// Get the local authentication context:
LAContext *context = [[LAContext alloc] init];

// Test if fingerprint authentication is available on the device and a fingerprint has been enrolled.
if ([context canEvaluatePolicy: LAPolicyDeviceOwnerAuthenticationWithBiometrics error:nil])
{
    NSLog(@"Fingerprint authentication available.");
}

仅验证指纹:

[context evaluatePolicy:LAPolicyDeviceOwnerAuthenticationWithBiometrics localizedReason:@"Authenticate for server login" reply:^(BOOL success, NSError *authenticationError){
    if (success) {
        NSLog(@"Fingerprint validated.");
    }
    else {
        NSLog(@"Fingerprint validation failed: %@.", authenticationError.localizedDescription);
    }
}];

根据用户的选择验证指纹或设备密码: 这超出了此处问题的范围,请在以下网址查找更多信息:https://www.secsign.com/fingerprint-validation-as-an-alternative-to-passcodes/


哎呀,想用Apple Watch测试Touch ID,我有一部iPhone6但没有手表。真希望我们可以使用模拟器来测试Touch ID。 - user1872384
现在有支持了,请参见下面的@karthik答案!这个答案应该更新一下:)) - thinklinux

1

适用于 xCode 12

功能 -> Touch ID

enter image description here


0

在 Objective-C 中

@import LocalAuthentication;

@interface EnterPasscodeVC ()


-(void)viewWillAppear:(BOOL)animated {
    LAContext *myContext = [[LAContext alloc] init];
    NSError *authError = nil;
    NSString *myLocalizedReasonString =  @"Authentication is required to access your QPay Apps.";

    if ([myContext canEvaluatePolicy:LAPolicyDeviceOwnerAuthenticationWithBiometrics error:&authError]) {
        [myContext evaluatePolicy:LAPolicyDeviceOwnerAuthenticationWithBiometrics
                  localizedReason:myLocalizedReasonString
                            reply:^(BOOL success, NSError *error) {
                                if (success) {
                                    dispatch_async(dispatch_get_main_queue(), ^{
                                        [self performSegueWithIdentifier:@"Success" sender:nil];
                                    });
                                } else {
                                    dispatch_async(dispatch_get_main_queue(), ^{

                                        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Error"
                                                                                            message:error.description
                                                                                           delegate:self
                                                                                  cancelButtonTitle:@"OK"
                                                                                  otherButtonTitles:nil, nil];
                                        [alertView show];


                                        switch (error.code) {
                                            case LAErrorAuthenticationFailed:
                                                NSLog(@"Authentication Failed");
                                                // Rather than show a UIAlert here, use the error to determine if you should push to a keypad for PIN entry.

                                                break;

                                            case LAErrorUserCancel:
                                                NSLog(@"User pressed Cancel button");
                                                break;

                                            case LAErrorUserFallback:
                                                NSLog(@"User pressed \"Enter Password\"");
                                                break;

                                            default:
                                                NSLog(@"Touch ID is not configured");
                                                break;
                                        }
                                        NSLog(@"Authentication Fails");




                                    });
                                }
                            }];
    } else {
        dispatch_async(dispatch_get_main_queue(), ^{
            UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Error"
                                                                message:authError.description
                                                               delegate:self
                                                      cancelButtonTitle:@"OK"
                                                      otherButtonTitles:nil, nil];
            [alertView show];
            // Rather than show a UIAlert here, use the error to determine if you should push to a keypad for PIN entry.
        });
    }
}

在 Swift 中

import LocalAuthentication


   override func viewDidLoad() {
        super.viewDidLoad()
        authenticateUser()
    }



  // MARK: Method implementation

    func authenticateUser() {
        // Get the local authentication context.
        let context = LAContext()

        // Declare a NSError variable.
        var error: NSError?

        // Set the reason string that will appear on the authentication alert.
        let reasonString = "Authentication is needed to access your notes."

        // 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 {
                    // If authentication was successful then load the data.
                    NSOperationQueue.mainQueue().addOperationWithBlock({ () -> Void in
                        self.loadData()
                    })
                }
                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")
                        NSOperationQueue.mainQueue().addOperationWithBlock({ () -> Void in
                            self.showPasswordAlert()
                        })


                    default:
                        print("Authentication failed")
                        NSOperationQueue.mainQueue().addOperationWithBlock({ () -> Void in
                            self.showPasswordAlert()
                        })
                    }
                }

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

            // Show the custom alert view to allow users to enter the password.
            showPasswordAlert()
        }
    }


    func showPasswordAlert() {
        let passwordAlert : UIAlertView = UIAlertView(title: "TouchIDDemo", message: "Please type your password", delegate: self, cancelButtonTitle: "Cancel", otherButtonTitles: "Okay")
        passwordAlert.alertViewStyle = UIAlertViewStyle.SecureTextInput
        passwordAlert.show()
    }


    func loadData(){
        if appDelegate.checkIfDataFileExists() {
            self.dataArray = NSMutableArray(contentsOfFile: appDelegate.getPathOfDataFile())
            self.tblNotes.reloadData()
        }
        else{
            print("File does not exist")
        }
    }


    // MARK: UIAlertViewDelegate method implementation

    func alertView(alertView: UIAlertView!, clickedButtonAtIndex buttonIndex: Int) {
        if buttonIndex == 1 {
            if !alertView.textFieldAtIndex(0)!.text!.isEmpty {
                if alertView.textFieldAtIndex(0)!.text == "appcoda" {
                    loadData()
                }
                else{
                    showPasswordAlert()
                }
            }
            else{
                showPasswordAlert()
            }
        }
    }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接