本來以為比較多的東西冰单,突然想做一下幌缝,查了下,就那么點東西球凰。
首先判斷系統版本,要求的最低版本為iOS8.0狮腿;
- (BOOL)checkDeviceSystemVersion {
NSString *systemVersion = [UIDevice currentDevice].systemVersion;
if (systemVersion.floatValue >= 8.0) {
return YES;
} else {
return NO;
} }
然后,導入所需要的庫
#import<LocalAuthentication/LocalAuthentication.h>;
之后就是固定寫法了:
//初始化對象
LAContext* context = [[LAContext alloc] init];
//錯誤對象
NSError* error = nil;
//這個是touchID下邊顯示的一行文字呕诉,一般用來說明為什么需要指紋認證
NSString* reason = @"需要進行指紋認證";
//touchID認證失敗以后出現 默認為"Enter Password",設定nil的話缘厢,這個選項會消失
context.localizedFallbackTitle = @"輸入密碼";
//默認為“cancel”
context.localizedCancelTitle = @"取消";
//首先使用canEvaluatePolicy 判斷設備支持狀態(tài)
if ([context canEvaluatePolicy:LAPolicyDeviceOwnerAuthenticationWithBiometrics error:&error]) {
//支持指紋驗證
[context evaluatePolicy:LAPolicyDeviceOwnerAuthenticationWithBiometrics localizedReason:reason reply:^(BOOL success, NSError *error) {
if (success) {
//驗證成功,主線程處理UI
NSLog(@"驗證成功");
UIAlertController *alert = [UIAlertController alertControllerWithTitle:nil message:@"驗證成功" preferredStyle:UIAlertControllerStyleAlert];
UIAlertAction *resetAction = [UIAlertAction actionWithTitle:@"再試一次" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
[self authenticationByFingerprint];
}];
UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {
}];
[alert addAction:resetAction];
[alert addAction:cancelAction];
[self presentViewController:alert animated:YES completion:^{
}];
}
else
{
NSLog(@"%@",error.localizedDescription);
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
{
//不支持指紋識別伊者,LOG出錯誤詳情
switch (error.code) {
case LAErrorTouchIDNotEnrolled:
{
NSLog(@"TouchID is not enrolled");
//touchID不可用 用戶未錄入
break;
}
case LAErrorPasscodeNotSet:
{
NSLog(@"A passcode has not been set");
//系統未設置密碼
break;
}
default:
{
NSLog(@"TouchID not available");
//touchID不可用 例如設備不支持
break;
}
}
NSLog(@"%@",error.localizedDescription);
}