How to use Touch ID sensor in iOS 8

2019-04-07 02:59发布

问题:

One of the most things I was excited about iOS 8 was the ability to use fingerprint sensors on the iPhone 5s and later. Unfortunately I cannot find out what is the required framework for that, nor how I can make authentication. Please help me with:

  • What framework required for using Touch ID?
  • How to use its methods and how to authenticate the user?

A code sample would be much appreciated.

回答1:

More complete snippet, swift style:

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.
        var 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 {

                }
                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.
                    println(evalPolicyError?.localizedDescription)

                    switch evalPolicyError!.code {

                    case LAError.SystemCancel.toRaw():
                        println("Authentication was cancelled by the system")

                    case LAError.UserCancel.toRaw():
                        println("Authentication was cancelled by the user")

                    case LAError.UserFallback.toRaw():
                        println("User selected to enter custom password")
                        self.showPasswordAlert()

                    default:
                        println("Authentication failed")
                        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.toRaw():
                println("TouchID is not enrolled")

            case LAError.PasscodeNotSet.toRaw():
                println("A passcode has not been set")

            default:
                // The LAError.TouchIDNotAvailable case.
                println("TouchID not available")
            }

            // Optionally the error description can be displayed on the console.
            println(error?.localizedDescription)

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

Source



回答2:

The Local Authentication framework provides facilities for requesting authentication from users using Touch ID, following code snipped shows how you should request for authentication.

Objective C

LAContext *myContext = [[LAContext alloc] init];
NSError *authError = nil;
NSString *myReasonString = @"String explaining why app needs authentication";

if ([myContext canEvaluatePolicy:LAPolicyDeviceOwnerAuthenticationWithBiometrics error:&authError]) {
    [myContext evaluatePolicy:LAPolicyDeviceOwnerAuthenticationWithBiometrics
                  localizedReason:myReasonString
                            reply:^(BOOL succes, NSError *error) {
            if (success) {
                // User authenticated successfully
            } else {
                // Authenticate failed
            }
        }];
} else {
    // Could not evaluate policy; check authError
}

Swift

let myContext = LAContext()
var authError: NSError?

// Set the reason string that will appear on the authentication alert.
var myReasonString = "String explaining why app needs authentication"

if myContext.canEvaluatePolicy(LAPolicy.DeviceOwnerAuthenticationWithBiometrics, error: &authError) {
    [myContext.evaluatePolicy(LAPolicy.DeviceOwnerAuthenticationWithBiometrics, localizedReason: myReasonString, reply: { (success: Bool, evalPolicyError: NSError?) -> Void in

        if success {
            // User authenticated successfully
        } else {
            // Authenticate failed
        }
    })]
} else{
    // Could not evaluate policy; check authError
}


回答3:

You're looking for LocalAuthentication framework (login may be required to see).

Basically you're interested in LAContext class and its canEvaluatePolicy:error: and evaluatePolicy:localizedReason:reply: methods.

The canEvaluatePolicy:error: method is used to check if TouchID authentication is available for you to use.

And use evaluatePolicy:localizedReason:reply: to perform actual authentication check



回答4:

I was looking for an answer in objectiveC with all the possible errors. Didn't find on this post so here it is.

LAContext *myContext = [[LAContext alloc] init];
    NSError *authError = nil;
    NSString *myLocalizedReasonString = @"Authenticate using your finger";
    if ([myContext canEvaluatePolicy:LAPolicyDeviceOwnerAuthenticationWithBiometrics error:&authError]) {
       [myContext evaluatePolicy:LAPolicyDeviceOwnerAuthenticationWithBiometrics
                     localizedReason:myLocalizedReasonString
                               reply:^(BOOL success, NSError *error) {
                                   if (success) {
                                       NSLog(@"User is authenticated successfully");
                                   } else {
                                       switch (error.code) {
                                           case LAErrorAuthenticationFailed:
                                               NSLog(@"Authentication Failed");
                                               break;

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

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

                                           case LAErrorPasscodeNotSet:
                                               NSLog(@"Passcode Not Set");
                                               break;

                                           case LAErrorTouchIDNotAvailable:
                                               NSLog(@"Touch ID not available");
                                               break;

                                           case LAErrorTouchIDNotEnrolled:
                                               NSLog(@"Touch ID not Enrolled or configured");
                                               break;

                                           default:
                                               NSLog(@"Touch ID is not configured");
                                               break;
                                       }
                                       NSLog(@"Authentication Fails");
                                   }
                               }];
    } else {
       NSLog(@"Can not evaluate Touch ID. This device doesn’t support one");
    }

Also make sure to use dispatch_async otherwise your uialert messages will not pop-up on time. See sample code below

-(void)viewWillAppear:(BOOL)animated {
    LAContext *myContext = [[LAContext alloc] init];
    NSError *authError = nil;
    NSString *myLocalizedReasonString = @"Touch ID Test to show Touch ID working in a custom app";

    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];
                                        // Rather than show a UIAlert here, use the error to determine if you should push to a keypad for PIN entry.
                                    });
                                }
                            }];
    } 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.
        });
    }
}


回答5:

Swift 3 version of @txulu response:

public 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.
    var 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 {
                // TODO - Guardar credencials
            }
            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")
                    //self.showPasswordAlert()

                default:
                    print("Authentication failed")
                    //self.showPasswordAlert()
                }
            }

        } as! (Bool, Error?) -> Void)]
    }
    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.
        //self.showPasswordAlert()
    }
}