功能需求:登錄之后,只要不退出登錄,再次進入app時需要驗證指紋后進入主頁面。
- (void)viewDidLoad {
[super viewDidLoad];
[self showFingerprintVerification];
}
// 指紋驗證
- (void)showFingerprintVerification {
// 初始化上下文對象
LAContext *context = [[LAContext alloc] init];
// 錯誤對象
NSError *error = nil;
NSString *result = @"通過Home鍵驗證已有手機指紋";
// 首先使用canEvaluatePolicy 判斷設備支持狀態
if ([context canEvaluatePolicy:LAPolicyDeviceOwnerAuthenticationWithBiometrics error:&error]) {
// 支持指紋驗證
[context evaluatePolicy:LAPolicyDeviceOwnerAuthenticationWithBiometrics localizedReason:result reply:^(BOOL success, NSError *error) {
if (success) {
NSLog(@"登錄成功");
[[NSOperationQueue mainQueue] addOperationWithBlock:^{
[[AppDelegate sharedAppDelegate] changeMainRootViewController];
}];
} else {
NSLog(@"%@",error.localizedDescription);
switch (error.code) {
case LAErrorSystemCancel: {
NSLog(@"切換到其他APP,系統取消驗證Touch ID");
break;
}
case LAErrorUserCancel: {
NSLog(@"用戶取消驗證Touch ID");
break;
}
case LAErrorUserFallback: {
[[NSOperationQueue mainQueue] addOperationWithBlock:^{
NSLog(@"用戶選擇輸入密碼,切換主線程處理");
// 登錄頁面
NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
[userDefaults setInteger:unLogin forKey:FYLOGINTIMES_Key];
[userDefaults synchronize];
[[AppDelegate sharedAppDelegate] changeRootViewController];
}];
break;
}
case LAErrorTouchIDLockout: { // iOS 9之后才會有的
[[NSOperationQueue mainQueue] addOperationWithBlock:^{
NSLog(@"多次指紋校驗失敗, 需要輸入密碼解鎖");
UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"指紋不匹配" message:nil preferredStyle:UIAlertControllerStyleAlert];
[self presentViewController:alert animated:NO completion:nil];
dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, 2.0 *NSEC_PER_SEC);
dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
[alert dismissViewControllerAnimated:YES completion:nil];
});
}];
break;
}
case LAErrorAppCancel: { // iOS 9之后才會有的
NSLog(@"當前app被掛起取消了授權,和LAErrorSystemCancel不太一樣");
break;
}
case LAErrorInvalidContext: { // iOS 9之后才會有的
NSLog(@"LAContext對象被釋放掉了,造成的授權失敗");
break;
}
default: {
[[NSOperationQueue mainQueue] addOperationWithBlock:^{
}];
break;
}
}
}
}];
} else {
// 不支持指紋識別,LOG出錯誤詳情
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);
}
}