#import "ViewController.h" #import <LocalAuthentication/LocalAuthentication.h> @interface ViewController () @end @implementation ViewController - (void)viewDidLoad { [super viewDidLoad]; // Do any additional setup after loading the view, typically from a nib. self.view.backgroundColor = [UIColor whiteColor]; UIButton *btn = [UIButton buttonWithType:UIButtonTypeSystem]; btn.frame = CGRectMake(100, 100, 100, 100); btn.backgroundColor = [UIColor orangeColor]; [btn setTitle:@"Touch ID" forState:UIControlStateNormal]; [btn addTarget:self action:@selector(action) forControlEvents:UIControlEventTouchUpInside]; [self.view addSubview:btn]; } -(void)action { LAContext *laContext =[[LAContext alloc]init]; NSError *error = nil; if ([laContext canEvaluatePolicy:LAPolicyDeviceOwnerAuthenticationWithBiometrics error:&error]){ [laContext evaluatePolicy:LAPolicyDeviceOwnerAuthenticationWithBiometrics localizedReason:@"Touch IDTest" reply:^(BOOL success, NSError * _Nullable error) { if (success){ NSLog(@"success to evaluate"); }else if (error){ NSLog(@"---failed----%@",error.description); switch (error.code) { case LAErrorSystemCancel: { NSLog(@"Authentication was cancelled by the system"); //切換到其餘APP,系統取消驗證Touch ID break; } case LAErrorUserCancel: { NSLog(@"Authentication was cancelled by the user"); //用戶取消驗證Touch ID break; } case LAErrorUserFallback: { NSLog(@"User selected to enter custom password"); [[NSOperationQueue mainQueue] addOperationWithBlock:^{ //用戶選擇輸入密碼,切換主線程處理 }]; break; } default: { [[NSOperationQueue mainQueue] addOperationWithBlock:^{ //其餘狀況,切換主線程處理 }]; break; } } } }]; }else{ NSLog(@"未調用TouchID=======%@=====",error.description); } } - (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; // Dispose of any resources that can be recreated. } @end typedef NS_ENUM(NSInteger, LAError) { //受權失敗 LAErrorAuthenticationFailed = kLAErrorAuthenticationFailed, //用戶取消Touch ID受權 LAErrorUserCancel = kLAErrorUserCancel, //用戶選擇輸入密碼 LAErrorUserFallback = kLAErrorUserFallback, //系統取消受權(例如其餘APP切入) LAErrorSystemCancel = kLAErrorSystemCancel, //系統未設置密碼 LAErrorPasscodeNotSet = kLAErrorPasscodeNotSet, //設備Touch ID不可用,例如未打開 LAErrorTouchIDNotAvailable = kLAErrorTouchIDNotAvailable, //設備Touch ID不可用,用戶未錄入 LAErrorTouchIDNotEnrolled = kLAErrorTouchIDNotEnrolled, } NS_ENUM_AVAILABLE(10_10, 8_0);
注:輸入錯誤時,alert下發會出現輸入密碼框ide