How to use touch ID sensor in iOS 8

One of the most interesting things that I worried about in iOS 8 was the ability to use fingerprint sensors on iPhone 5 and later. Unfortunately, I can’t find out why this is necessary and how I can do authentication. Please help me:

  • What framework is needed to use Touch ID?
  • How to use its methods and how to authenticate a user?

It would be very helpful to evaluate the sample code.

+8
source share
6 answers

More complete fragment, quick 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() } } 

A source

+9
source

The Local Authentication structure provides a means to request authentication of users using Touch IDs, after the code is disabled, it shows how you should request authentication.

Goal 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 } 
+6
source

You are looking for a LocalAuthentication framework (login may be required).

You are mainly interested in the LAContext class and its canEvaluatePolicy:error: and evaluatePolicy:localizedReason:reply:

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

And use evaluatePolicy:localizedReason:reply: to authenticate with authentication

+3
source

I searched for the answer in lens C with all possible errors. I did not 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 remember to use dispatch_async, otherwise your uialert messages will not pop up on time. See code example 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. }); } } 
+3
source

Swift 3 version of @txulu's answer:

 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() } } 
+1
source

Among these answers, I got stuck every time I ran an authentication code.

Make sure you import LocalAuthentication to use LAContext and verify privacy

With Swift 5, this is what worked for me.

 import UIKit import LocalAuthentication class ViewController: UIViewController { @IBOutlet weak var lbl: UILabel! override func viewDidLoad() { super.viewDidLoad() } @IBAction func checkUserAuthentication(_ sender: Any) { let context = LAContext() var error: NSError? if context.canEvaluatePolicy(.deviceOwnerAuthenticationWithBiometrics, error: &error) { let reason = "Identify yourself!" context.evaluatePolicy(.deviceOwnerAuthenticationWithBiometrics, localizedReason: reason) { [unowned self] success, authenticationError in DispatchQueue.main.async { if success { //Authentication Success self.lbl.text = "Great!! you are authorised" } else { let ac = UIAlertController(title: "Authentication failed", message: "Sorry!", preferredStyle: .alert) ac.addAction(UIAlertAction(title: "OK", style: .default)) self.present(ac, animated: true) } } } } else { let ac = UIAlertController(title: "Touch ID not available", message: "Your device is not configured for Touch ID.", preferredStyle: .alert) ac.addAction(UIAlertAction(title: "OK", style: .default)) present(ac, animated: true) } } } 
0
source

Source: https://habr.com/ru/post/970681/


All Articles