如何在iOS 8中使用Touch ID传感器

时间:2014-06-11 08:26:26

标签: ios swift iphone ios8 touch-id

我对iOS 8感到兴奋的最重要的事情之一是能够在iPhone 5s及更高版本上使用指纹传感器。不幸的是,我无法找到它所需的框架,也不知道如何进行身份验证。请帮帮我:

  • 使用Touch ID需要什么框架?
  • 如何使用其方法以及如何对用户进行身份验证?

非常感谢代码示例。

7 个答案:

答案 0 :(得分:9)

更完整的代码片段,快捷风格:

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

答案 1 :(得分:6)

本地身份验证框架提供了使用Touch ID向用户请求身份验证的功能,下面的代码剪辑显示了您应该如何请求身份验证。

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

<强>夫特

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
}

答案 2 :(得分:3)

您正在寻找LocalAuthentication framework(可能需要登录才能看到)。

基本上你对LAContext类及其感兴趣 canEvaluatePolicy:error:evaluatePolicy:localizedReason:reply:方法。

canEvaluatePolicy:error:方法用于检查您是否可以使用TouchID身份验证。

使用evaluatePolicy:localizedReason:reply:执行实际身份验证检查

答案 3 :(得分:3)

我在objectiveC中寻找答案,包含所有可能的错误。在这篇文章中没有找到,所以在这里。

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

另外请确保使用dispatch_async,否则您的uialert消息将不会按时弹出。请参阅下面的示例代码

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

答案 4 :(得分:1)

Swift 3版本的@txulu回复:

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

答案 5 :(得分:0)

在这些答案中,每次运行身份验证代码时,我都会被卡住。

请确保您导入LocalAuthentication 以使用LAContext和隐私检查

使用 Swift 5 对我有用。

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

答案 6 :(得分:0)

完整的 Swift 5 版本示例片段:

import LocalAuthentication

_

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 provide access."

    // 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: Error?) -> Void in

            if success {
                print("Authentication successful! :) ")
            }
            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.authenticationFailed.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()
                }
            }

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

func showPasswordAlert() {
    print("### showPasswordAlert")
}