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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25459059/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 02:00:58  来源:igfitidea点击:

Is there any way to use apple's Touch ID (fingerprint scanner) on iOS Simulator?

iosiphoneios-simulatorios8touch-id

提问by Ashish

I am working on an app which would require Touch ID Authentication, so is there any way i can use Touch ID (fingerprint scanner) in the simulator ?

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

Also, please do share some kind of example code for using LocalAuthentication framework.

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

采纳答案by Woodstock

As of Xcode 7 the Simulator supports 'touchID'. Answer below contains further info.

从 Xcode 7 开始,模拟器支持“touchID”。下面的答案包含更多信息。

As of the latest beta (6) there is no way to simulate a fingerprint scan on the simulator. To be honest I doubt this will be included even in later betas.

从最新的测试版 (6) 开始,无法在模拟器上模拟指纹扫描。老实说,我怀疑即使在以后的测试版中也会包含它。

You will need to test on device.

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

To use the Authentication framework right now you need: * XCode 6 * iPhone 5s with iOS 8

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

The steps you need to perform are:

您需要执行的步骤是:

Find out whether the device supports fingerprint validation and whether a fingerprint is enrolled:

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

@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.");
}

Validate a fingerprint only:

仅验证指纹:

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

Validate a fingerprint or the device's passcode depending on the user's choice:This is a little beyond the scope of a question here, please find more information at: https://www.secsign.com/fingerprint-validation-as-an-alternative-to-passcodes/

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

回答by karthik

XCODE 7 beta supports testing the Touch ID Authentication in iPhone Simulator.You can try this for your testing.

XCODE 7 beta 支持在 iPhone 模拟器中测试 Touch ID 身份验证。你可以试试这个来进行测试。

[Screenshot 1]

[截图1]

[Screenshot 1]

[截图1]

[Screenshot 2]

[截图2]

[Screenshot 2]

[截图2]

回答by Nischal Hada

In Objective c

在目标 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.
        });
    }
}

In 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()
            }
        }
    }