'How do I create a button that resets the authentication status in SwiftUI?
In my app I have a login page where registered users can either type their pin code or use Touch/Face ID to unlock the app. I have this code for the authentication:
class AuthenticationManager {
let context = LAContext()
var error: NSError?
func authenticate(closure: @escaping(_ : Bool)->()) {
if context.canEvaluatePolicy(.deviceOwnerAuthenticationWithBiometrics, error: &error) {
let reason = "Authentication through Face/Touch ID"
context.evaluatePolicy(.deviceOwnerAuthenticationWithBiometrics, localizedReason: reason) { success, authenticationError in
if success {
closure(true)
} else {
closure(false)
}
}
} else {
closure(false)
}
}
func lockDevice() {
context.invalidate()
}
}
I was trying to add a button as a navigation bar item that allowed the user to lock the app and get back to the login page where he/she has to insert the pin code to access their data (or authenticate again with Touch/Face ID), like this:
struct ContentView : View {
@State var authenticated = false
let am = AuthenticationManager()
var body : some View {
NavigationView {
VStack {
if authenticated {
HomePage()
} else {
Login()
.onAppear {
am.authenticate { value in
authenticated = value
}
}
}
}
.navigationBarItems(trailing:
Button {
withAnimation {
authenticated = false
am.lockDevice()
}
} label: {
Image(systemName: "lock.open")
.foregroundColor(.yellow)
.padding()
}
)
}
}
}
However, the lockDevice() function as I wrote it completely blocks the usage of biometric authentication, while I wanted to lock the app. I tried to simply put the authenticated bool on false: it show the Login page, but it's as if you're already authenticated. I tried covering the camera, but instead of the message "Face not authenticated" (which would indicate that the device had actually re-locked the biometric authentication) you get authenticated without any kind of face/finger check. How can I fix this?
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
