Created
October 12, 2023 08:54
Biometrics
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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