xcode 触控 ID 与面容 ID 代码
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/48810153/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Touch ID vs Face ID code
提问by kAiN
I wanted to ask a question about biometric authentication. In my app I entered authentication with Touch ID. Now voelvo implement the method with Face ID.
我想问一个关于生物识别认证的问题。在我的应用程序中,我使用 Touch ID 输入了身份验证。现在voelvo用Face ID来实现这个方法。
I inserted the line Privacy - Face ID Usage Descriptioninto my .plist file
我在我的 .plist 文件中插入了一行 Privacy - Face ID Usage Description
Now I have noticed that my Face ID works correctly without making any changes to the TouchID code.
现在我注意到我的 Face ID 可以正常工作,而无需对 TouchID 代码进行任何更改。
My question is :
我的问题是:
** The Touch ID implementation code identical to that of the Face ID? Can I leave the Touch ID implementation code without making any changes or do I have to add a few lines of code for Face ID?**
** Touch ID 实现代码和 Face ID 一样吗?我可以保留 Touch ID 实现代码而不做任何更改,还是必须为 Face ID 添加几行代码?**
I show you how I implemented my Touch ID
我向你展示我是如何实现我的 Touch ID
#pragma mark - TOUCH ID Login
-(void)useTouchID {
NSError *error;
LAContext *context = [[LAContext alloc] init];
NSString *emailAccount = [KFKeychain loadObjectForKey:USER_EMAIL];
NSString *reasonString = [NSString stringWithFormat:@"Autentica %@ utilizzando la tua impronta", emailAccount];
if ([context canEvaluatePolicy:kLAPolicyDeviceOwnerAuthenticationWithBiometrics error:&error]) {
[context evaluatePolicy:kLAPolicyDeviceOwnerAuthenticationWithBiometrics localizedReason: reasonString reply:^(BOOL success, NSError * _Nullable error) {
// Se la procedura con il TouchID va a buon fine settiamo il booleano su YES che specifica se l'utente a scelto di utilizzare il TouchID oppure NO.
// Successivamente invochiamo il metodo loginWithFirebase per procedere con l'autenticazione su firebase
dispatch_async(dispatch_get_main_queue(), ^{
[APPDELEGATE showHud];
});
if (success) {
_useBiometricsAuthentication = YES;
// Attualmente il TouchID non viene supportato da Firebase pertanto dobbiamo autenticarci con l'impronta digitale e successivamente eseguire il login con Firebase.
[self useFirebaseSignIn];
}
// Nel caso in cui si verifichino alcuni errori con l'uso del TouchID andiamo ad implementare ogni singolo errore che l'utente puo' riscontrare
else {
_useBiometricsAuthentication = NO;
switch ([error code]) {
// L'autenticazione con Touch ID è fallità
case kLAErrorAuthenticationFailed:
NSLog(@"Autenticazione Fallita");
dispatch_async(dispatch_get_main_queue(), ^{
[APPDELEGATE removeHud];
});
break;
// L'user ha spinto annulla sull'alert che compare sulla richiesta di TouchID oppure ha spinto il pulsante Home facendo scomparire l'alert
case kLAErrorUserCancel:
NSLog(@"User ha respinto il touch ID");
dispatch_async(dispatch_get_main_queue(), ^{
[APPDELEGATE removeHud];
});
break;
// In questo caso l'user ha piu volte tentato di utilizzare il touchID e ha preferito inserire le proprie credenziali manualmente
case kLAErrorUserFallback:
NSLog(@"L'user ha scelto di utilizzare il login di firebase");
// a questo punto eliminiamo tutti i dati salvati con il login precedente in modo tale da poter salvare nuovamente le credenziali che l'utente ha inserito manualmente
[self deleteUserKey];
dispatch_async(dispatch_get_main_queue(), ^{
[APPDELEGATE removeHud];
});
break;
// L'errore ci comunica che l'utente molto probabilmente non ha mai inserito / salvato le proprie impronte digitali nel suo dispositivo
case kLAErrorTouchIDNotEnrolled:
NSLog(@" non sono state impostate impronte per utilizzare il touch id");
dispatch_async(dispatch_get_main_queue(), ^{
[APPDELEGATE showAlertWithTitle:@"ATTENZIONE" message:@"Il TUOCH ID ha bisogno di avere delle impronte digitali impostate per poter funzionare. Vai sulle IMPOSTAZIONI del tuo dispositivo in TOUCH ID e CODICE per inserirle" optionTitle:@"OK" otherOptionTitle:nil optionButtonAction:^{
[APPDELEGATE dismissAlert];
} canButtonAction:nil];
[APPDELEGATE removeHud];
});
break;
// In questo caso ci avverte che per utilizzare il TouchID l'app deve aver salvato almeno una volte le credenziali che l'utente inserisce manualmente, all'interno di un portachiavi come ad esempio la libreria utilizzata in questa app (Keychain)
case kLAErrorPasscodeNotSet: {
NSLog(@"il touch id ha bisogno di avere dei codici di accesso salvati per essere usato");
dispatch_async(dispatch_get_main_queue(), ^{
[APPDELEGATE showAlertWithTitle:@"ATTENZIONE" message:@"Sembra che non vi sia nessun account collegato a queste impronte. Perfavore effettua il login classico utilizzando la tua Email e la tua Password del tuo account Unistit e riprova." optionTitle:@"OK" otherOptionTitle:nil optionButtonAction:^{
[APPDELEGATE dismissAlert];
[self.emailField becomeFirstResponder];
[self deleteUserKey];
} canButtonAction:nil];
[APPDELEGATE removeHud];
});
break;
}
default:
break;
}
}
}];
}
}
采纳答案by Quentin Hayot
You don't have to update your code to be Face ID ready if your app already supports Touch ID.(as seen here)
iOS takes care of all the work under the hood.
如果您的应用程序已经支持 Touch ID,则您无需更新代码即可使用 Face ID。(如看到这里)
的iOS需要引擎盖下照顾所有的工作。
What you can do however, is to change your strings containing "Touch ID" to "Face ID" if the app is running on a Face ID capable device.
但是,如果应用程序在支持 Face ID 的设备上运行,您可以做的是将包含“Touch ID”的字符串更改为“Face ID”。
Edit:As noted by MikeMertsock, the LAContextclass has a biometryType
property to determine whether the device uses Touch ID or Face ID.
编辑:正如MikeMertsock所指出的,LAContext类有一个biometryType
属性来确定设备是使用 Touch ID 还是 Face ID。
回答by Krunal
You may be looking for this: biometryType
is used to specify/update some localisables for user information only. Your working code will automatically identify biometryType and handle authentication operations. You don't need to update it.
您可能正在寻找这个:biometryType
仅用于为用户信息指定/更新一些本地化。您的工作代码将自动识别 biometryType 并处理身份验证操作。你不需要更新它。
Here is sample code, how you can manually detect, which biometry type is supported by device.
这是示例代码,如何手动检测设备支持哪种生物识别类型。
LAContext *laContext = [[LAContext alloc] init];
NSError *error;
if ([laContext canEvaluatePolicy:LAPolicyDeviceOwnerAuthenticationWithBiometrics error:&error]) {
if (error != NULL) {
// handle error
} else {
if (@available(iOS 11.0.1, *)) {
if (laContext.biometryType == LABiometryTypeFaceID) {
//localizedReason = "Unlock using Face ID"
NSLog(@"FaceId support");
} else if (laContext.biometryType == LABiometryTypeTouchID) {
//localizedReason = "Unlock using Touch ID"
NSLog(@"TouchId support");
} else {
//localizedReason = "Unlock using Application Passcode"
NSLog(@"No Biometric support");
}
} else {
// Fallback on earlier versions
}
[laContext evaluatePolicy:LAPolicyDeviceOwnerAuthenticationWithBiometrics localizedReason:@"Test Reason" reply:^(BOOL success, NSError * _Nullable error) {
if (error != NULL) {
// handle error
} else if (success) {
// handle success response
} else {
// handle false response
}
}];
}
}
回答by Priya
func authenticateUser() {
// Get the local authentication context.
let context = LAContext()
// Declare a NSError variable.
// Set the reason string that will appear on the authentication alert.
_ = "Authentication is needed to access your notes."
var policy: LAPolicy?
// Depending the iOS version we'll need to choose the policy we are able to use
if #available(iOS 9.0, *) {
// iOS 9+ users with Biometric and Passcode verification
policy = .deviceOwnerAuthentication
} else {
// iOS 8+ users with Biometric and Custom (Fallback button) verification
context.localizedFallbackTitle = "Fuu!"
policy = .deviceOwnerAuthenticationWithBiometrics
}
context.evaluatePolicy(policy!, localizedReason: "Please Add your touch Id", reply: { (success, error) in
DispatchQueue.main.async {
RKDropdownAlert.title(NSLocalizedString("Success", comment: ""), message: NSLocalizedString("User Touch Id Enrolled Successfully", comment: ""), backgroundColor: BMConstants.KAppBGColor, textColor: BMConstants.KAppWhiteColor)
guard success else {
guard let error = error else {
return
}
switch(error) {
case LAError.authenticationFailed:
//self.message.text = "There was a problem verifying your identity."
break
case LAError.userCancel:
RKDropdownAlert.title(NSLocalizedString("Error", comment: ""), message: NSLocalizedString("User cancelled", comment: ""), backgroundColor: BMConstants.KAppBGColor, textColor: BMConstants.KAppWhiteColor)
// self.message.text = "Authentication was canceled by user."
// Fallback button was pressed and an extra login step should be implemented for iOS 8 users.
// By the other hand, iOS 9+ users will use the pasccode verification implemented by the own system.
break
case LAError.userFallback:
RKDropdownAlert.title(NSLocalizedString("Error", comment: ""), message: NSLocalizedString("The user tapped the fallback", comment: ""), backgroundColor: BMConstants.KAppBGColor, textColor: BMConstants.KAppWhiteColor)
//self.message.text = "The user tapped the fallback button (Fuu!)"
break
case LAError.systemCancel:
RKDropdownAlert.title(NSLocalizedString("Error", comment: ""), message: NSLocalizedString("Authentication was canceled by system", comment: ""), backgroundColor: BMConstants.KAppBGColor, textColor: BMConstants.KAppWhiteColor)
// self.message.text = "Authentication was canceled by system."
break
case LAError.passcodeNotSet:
RKDropdownAlert.title(NSLocalizedString("Error", comment: ""), message: NSLocalizedString("Passcode is not set on the device", comment: ""), backgroundColor: BMConstants.KAppBGColor, textColor: BMConstants.KAppWhiteColor)
// self.message.text = "Passcode is not set on the device."
break
case LAError.touchIDNotAvailable:
RKDropdownAlert.title(NSLocalizedString("Error", comment: ""), message: NSLocalizedString("Touch ID is not available on the device", comment: ""), backgroundColor: BMConstants.KAppBGColor, textColor: BMConstants.KAppWhiteColor)
// self.message.text = "Touch ID is not available on the device."
break
case LAError.touchIDNotEnrolled:
RKDropdownAlert.title(NSLocalizedString("Error", comment: ""), message: NSLocalizedString("TTouch ID has no enrolled fingers", comment: ""), backgroundColor: BMConstants.KAppBGColor, textColor: BMConstants.KAppWhiteColor)
// self.message.text = "Touch ID has no enrolled fingers."
break
// iOS 9+ functions
case LAError.touchIDLockout:
RKDropdownAlert.title(NSLocalizedString("Error", comment: ""), message: NSLocalizedString("here were too many failed Touch ID attempts and Touch ID is now locked", comment: ""), backgroundColor: BMConstants.KAppBGColor, textColor: BMConstants.KAppWhiteColor)
break
case LAError.appCancel:
RKDropdownAlert.title(NSLocalizedString("Error", comment: ""), message: NSLocalizedString("Authentication was canceled by application", comment: ""), backgroundColor: BMConstants.KAppBGColor, textColor: BMConstants.KAppWhiteColor)
// self.message.text = "Authentication was canceled by application."
break
case LAError.invalidContext:
RKDropdownAlert.title(NSLocalizedString("Error", comment: ""), message: NSLocalizedString("LAContext passed to this call has been previously invalidated.", comment: ""), backgroundColor: BMConstants.KAppBGColor, textColor: BMConstants.KAppWhiteColor)
// self.message.text = "LAContext passed to this call has been previously invalidated."
break
default:
RKDropdownAlert.title(NSLocalizedString("Error", comment: ""), message: NSLocalizedString("Touch ID may not be configured", comment: ""), backgroundColor: BMConstants.KAppBGColor, textColor: BMConstants.KAppWhiteColor)
// self.message.text = "Touch ID may not be configured"
break
}
return
}
}
}
)
}