我对 iOS 8 最兴奋的事情之一就是能够在 iPhone 5s 及更高版本上使用指纹传感器。不幸的是,我无法找到所需的框架,也无法找到如何进行身份验证。请帮助我:
- 使用 Touch ID 需要什么框架?
- 如何使用它的方法以及如何对用户进行身份验证?
代码示例将不胜感激。
更完整的片段,快速的风格:
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()
}
}
本地身份验证框架提供了使用 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
}
我在 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.
});
}
}
您正在寻找LocalAuthentication 框架(可能需要登录才能查看)。
基本上你对 LAContext 类及其
canEvaluatePolicy:error:
方法
evaluatePolicy:localizedReason:reply:
感兴趣。
该canEvaluatePolicy:error:
方法用于检查 TouchID 身份验证是否可供您使用。
并用于evaluatePolicy:localizedReason:reply:
执行实际的身份验证检查
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()
}
}
完整的 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.biometryNotEnrolled.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")
}
在这些答案中,我每次运行身份验证代码时都会卡住。
请确保您导入 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)
}
}
}