Skip to content

Instantly share code, notes, and snippets.

@vitsky91
Created August 25, 2022 08:54
Show Gist options
  • Save vitsky91/46be8a7833298271de1ff261dec36a28 to your computer and use it in GitHub Desktop.
Save vitsky91/46be8a7833298271de1ff261dec36a28 to your computer and use it in GitHub Desktop.
BiometricAuth
import LocalAuthentication
class BiometricAuth {
var context = LAContext()
var error: NSError?
func auth(_ completion: @escaping (_ success: Bool) -> ()) {
// Get the supported biometry
var biometry = context.biometryType
// Check for biometric authentication
// permissions
var permissions = context.canEvaluatePolicy(
.deviceOwnerAuthentication,
error: &error
)
if permissions {
let reason = "Log in with Face ID"
context.evaluatePolicy(
// .deviceOwnerAuthentication allows
// biometric or passcode authentication
.deviceOwnerAuthentication,
localizedReason: reason
) { success, error in
if success {
// Handle successful authentication
} else {
self.error = error as? NSError
self.handleErrors()
}
completion(success)
}
} else {
// Handle permission denied or error
}
}
func handleErrors() {
// If error is an instance of LAError
var code = LAError.Code(rawValue: error!.code)
switch code {
case .appCancel:
break
// The app canceled authentication by
// invalidating the LAContext
case .authenticationFailed:
break
// The user did not provide
// valid credentials
case .invalidContext:
break
// The LAContext was invalid
case .notInteractive:
break
// Interaction was not allowed so the
// authentication failed
case .passcodeNotSet:
break
// The user has not set a passcode
// on this device
case .systemCancel:
break
// The system canceled authentication,
// for example to show another app
case .userCancel:
break
// The user canceled the
// authentication dialog
case .userFallback:
break
// The user selected to use a fallback
// authentication method
case .biometryLockout:
break
// Too many failed attempts locked
// biometric authentication
case .biometryNotAvailable:
break
// The user's device does not support
// biometric authentication
case .biometryNotEnrolled:
break
// The user has not configured
// biometric authentication
@unknown default:
break
// An other error occurred
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment