- Xcode 8.1 or later
- iOS 8.0 or later
引入指紋解鎖必須的頭文件
#import <LocalAuthentication/LocalAuthentication.h>
判斷設備是否支持TouchID
- (BOOL)canEvaluatePolicy:(LAPolicy)policy error:(NSError * __autoreleasing *)error __attribute__((swift_error(none)));
彈出框出來驗證TouchID,Block返回成功和失敗的回調
- (void)evaluatePolicy:(LAPolicy)policy localizedReason:(NSString *)localizedReason reply:(void(^)(BOOL success, NSError * __nullable error))reply;
驗證的例子
//初始化上下文對象
LAContext* context = [[LAContext alloc] init];
//錯誤對象
NSError* error = nil;
NSString* result = @"Authentication is needed to access your notes.";
//首先使用canEvaluatePolicy 判斷設備支持狀態
if ([context canEvaluatePolicy:LAPolicyDeviceOwnerAuthenticationWithBiometrics error:&error]) {
//支持指紋驗證
[context evaluatePolicy:LAPolicyDeviceOwnerAuthenticationWithBiometrics localizedReason:result reply:^(BOOL success, NSError *error) {
if (success) {
//驗證成功,主線程處理UI
}
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");
break;
}
case LAErrorPasscodeNotSet:
{
NSLog(@"A passcode has not been set");
break;
}
default:
{
NSLog(@"TouchID not available");
break;
}
}
NSLog(@"%@",error.localizedDescription);
}
幾種返回的錯誤的枚舉值
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);
}
Touch ID的簡單例子:https://github.com/smanx/Touch-ID-Demo