注:接入指紋驗證之前確定您的裝置是否支援 TouchID 功能并能正常使用的裝置(iPhone 5s 及以上)。
#import "ViewController.h"
#import <LocalAuthentication/LocalAuthentication.h> //需要導入這個庫檔案
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
if ([[self.navigationController.viewControllers firstObject] isEqual:self]) {
self.navigationItem.title = @"點選調用指紋識别";
}
}
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
[self touch];
}
- (void)touch {
if ([[self.navigationController.viewControllers firstObject] isEqual:self]) {
self.navigationItem.title = @"指紋驗證";
//定義一個alter按鈕
LAContext *context = [LAContext new]; //這個屬性是設定指紋輸入失敗之後的彈出框的選項
context.localizedFallbackTitle = @"輸入密碼"; // 按鈕的标題
NSError *error = nil;
//判斷使用者的手機是否支援指紋
if ([context canEvaluatePolicy:LAPolicyDeviceOwnerAuthenticationWithBiometrics
error:&error]) {
NSLog(@"支援指紋識别");
[context evaluatePolicy:LAPolicyDeviceOwnerAuthenticationWithBiometrics
localizedReason:@"指紋登入"
reply:^(BOOL success, NSError * _Nullable error) {
//這裡是指紋驗證之後傳回資訊
//隻傳回 success 值為 TRUE 或 FALSE
if (success) {
NSLog(@"驗證成功 你可以登入了 Go Go");
} else {
NSLog(@"%@",error.localizedDescription);
switch (error.code) {
case LAErrorSystemCancel: {
NSLog(@"系統取消授權,如其他APP切入");
break;
}
case LAErrorUserCancel: {
NSLog(@"使用者取消驗證Touch ID");
break;
}
case LAErrorAuthenticationFailed: {
NSLog(@"授權失敗");
break;
}
case LAErrorPasscodeNotSet: {
NSLog(@"系統未設定密碼");
break;
}
case LAErrorTouchIDNotAvailable: {
NSLog(@"裝置Touch ID不可用,例如未打開");
break;
}
case LAErrorTouchIDNotEnrolled: {
NSLog(@"裝置Touch ID不可用,使用者未錄入");
break;
}
case LAErrorUserFallback: {
[[NSOperationQueue mainQueue] addOperationWithBlock:^{
NSLog(@"使用者選擇輸入密碼,切換主線程處理");
}];
break;
}
default: {
[[NSOperationQueue mainQueue] addOperationWithBlock:^{
NSLog(@"其他情況,切換主線程處理");
}];
break;
}
}
}
}];
} else {
NSLog(@"不支援指紋識别");
switch (error.code) {
case LAErrorTouchIDNotEnrolled: {
NSLog(@"TouchID is not enrolled");
break;
}
case LAErrorPasscodeNotSet: {
NSLog(@"A passcode has not been set");
break;
}
default: {
NSLog(@"TouchID not available");
break;
}
}
NSLog(@"%@",error.localizedDescription);
}
}
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
}
@end
項目源碼請點選這裡