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

我对iOS 8感到兴奋的最多的事情之一就是能够在iPhone 5s及更高版本上使用指纹传感器。 不幸的是,我不能找出什么是必要的框架,也不能如何进行身份validation。 请帮助我:

  • 使用Touch ID需要什么框架?
  • 如何使用其方法以及如何validation用户?

代码示例将不胜感激。

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

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

资源

本地身份validation框架为使用Touch ID的用户提供了请求身份validation的function,下面的代码示例显示了如何请求身份validation。

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

您正在寻找LocalAuthentication框架 (可能需要login才能看到)。

基本上你对LAContext类和它的canEvaluatePolicy:error:evaluatePolicy:localizedReason:reply:方法感兴趣。

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

并使用evaluatePolicy:localizedReason:reply:执行实际的身份validation检查

我正在寻找一个在ObjectiveC中的答案,所有可能的错误。 没有find这个职位,所以在这里。

 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消息不会按时popup。 看下面的示例代码

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

@txulu响应的Swift 3版本:

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