Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //
- // Biometrics.swift
- // Local Auth Demo
- //
- // Created by Rayhan Nabi on 1/12/19.
- // Copyright © 2019 Rayhan Janam. All rights reserved.
- //
- import UIKit
- import LocalAuthentication
- enum BiometryType {
- case faceID
- case touchID
- case none
- }
- protocol BiometricAuthentication {
- func didAuthenticate()
- func didFailAuthentication(error: Error)
- }
- final class Biometrics {
- static func getInstance(usePasscode: Bool) -> GenericBiometrics {
- if #available(iOS 11.0, *) {
- return RegularBiometrics(usePasscode)
- } else {
- return FallbackBiometrics(usePasscode)
- }
- }
- }
- class GenericBiometrics {
- private var policy: LAPolicy
- let context: LAContext
- var isSensorAvailable: Bool {
- return context.canEvaluatePolicy(policy,
- error: nil)
- }
- var biometryType: BiometryType {
- return .none
- }
- var delegate: BiometricAuthentication?
- init(_ usePasscode: Bool) {
- context = LAContext()
- policy = usePasscode ? .deviceOwnerAuthentication : .deviceOwnerAuthenticationWithBiometrics
- }
- func authenticate(reason: String) {
- context.evaluatePolicy(policy, localizedReason: reason) { (result, error) in
- DispatchQueue.main.async {
- self.handleAuthState(result: result, error: error)
- self.context.invalidate()
- }
- }
- }
- private func handleAuthState(result: Bool, error: Error?) {
- if result {
- delegate?.didAuthenticate()
- } else {
- guard let error = error else { return }
- delegate?.didFailAuthentication(error: error)
- }
- }
- }
- @available(iOS 11.0, *)
- final class RegularBiometrics: GenericBiometrics {
- override var biometryType: BiometryType {
- if isSensorAvailable {
- switch context.biometryType {
- case .faceID:
- return .faceID
- case .touchID:
- return .touchID
- case .none:
- return .none
- }
- }
- return .none
- }
- }
- final class FallbackBiometrics: GenericBiometrics {
- override var biometryType: BiometryType {
- if isSensorAvailable {
- return .touchID
- }
- return .none
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement