Skip to content

Instantly share code, notes, and snippets.

@kk-vv
Created October 12, 2023 08:54
Show Gist options
  • Save kk-vv/25f68639ec9d57be2b41ad7999cd1bf9 to your computer and use it in GitHub Desktop.
Save kk-vv/25f68639ec9d57be2b41ad7999cd1bf9 to your computer and use it in GitHub Desktop.
Biometrics
import UIKit
import LocalAuthentication
class BiometricsUtils {
//Should not be singleton as always success after first time checked
//static let shared: BiometricsUtils = .init()
private lazy var context = LAContext()
init() {
_ = askBiometricAvailability() //then get context.biometryType
}
var bioType: LABiometryType {
context.biometryType
}
var availability: Bool {
bioType == .faceID || bioType == .touchID
}
func askBiometricAvailability() -> (Bool, NSError?) {
var error : NSError?
let result = context.canEvaluatePolicy(.deviceOwnerAuthenticationWithBiometrics, error: &error)
return (result, error)
}
/// Must call after viewDidAppear or will block viewDidLoad
func authenticate(completion : @escaping (Result<Bool, LAError>) -> Void){
Task {
do {
try await context.evaluatePolicy(.deviceOwnerAuthenticationWithBiometrics, localizedReason: "Log in to your wallet")
await MainActor.run {
completion(.success(true))
}
} catch {
await MainActor.run {
if let error = error as? LAError {
switch error.code {
case .biometryNotAvailable:
UIAlertController.showAlert(
withTitle: "Biometry Not Available",
message: "Open in setting?",
buttonTexts: [
R.string.localizable.buttonYes(preferredLanguages: .currentLang),
R.string.localizable.buttonNo(preferredLanguages: .currentLang)
],
action: { index in
if index == 0 {
UIApplication.shared.open(
URL(string: UIApplication.openSettingsURLString)!,
options: [:],
completionHandler: nil
)
completion(.failure(error))
} else { // Absolutelly no
completion(.success(false))
}
}
)
default:
completion(.failure(error))
println(error.localizedDescription)
}
}
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment