Table of Contents

    Book an Appointment

    INTRODUCTION: HOW DID WE DISCOVER THIS FACE ID ANOMALY?

    While working on a FinTech application featuring robust biometric security, we implemented a fallback authentication mechanism using Face ID and device passcodes. During intensive quality assurance and edge-case testing, we encountered a situation where the authentication flow exhibited intermittent, unpredictable behavior.

    The scenario unfolded like this: On a fresh installation, a user navigates to the login screen, enters valid credentials and grants biometric permissions. The OS Face ID prompt appears. To test the fallback, the user hides their face from the camera until the system presents the “Enter Passcode” screen. The user then clicks “Cancel” on the passcode screen.

    This sequence resulted in two distinct outcomes. Most of the time, the app gracefully cancelled the authentication and navigated to the expected dashboard view. However, in about 30% of our test runs, the Face ID prompt reappeared immediately after cancellation. If the user successfully authenticated during this unexpected second prompt, the application stalled. The success callback was never invoked, trapping the user in an unresolved UI state.

    Tech leaders who hire iOS developers for enterprise apps know that handling OS-level interruptions is critical for user trust. An unreliable authentication flow in a financial application is unacceptable. This challenge inspired this article to help teams properly synchronize Apple’s LocalAuthentication framework with modern declarative UI paradigms, avoiding orphaned callbacks and infinite prompt loops.

    PROBLEM CONTEXT: WHY DOES THE BIOMETRIC AUTHENTICATION FLOW BREAK?

    In our architecture, the biometric flow was integrated into a SwiftUI layer using the Combine framework to manage asynchronous state updates. The authentication use case relied on the standard LAContext to evaluate the biometric policy.

    The issue surfaced at the intersection of OS-level authentication dialogs and SwiftUI’s reactive view lifecycle. When a user interacts with a system-level prompt (like Face ID or the Passcode fallback), the app is temporarily moved out of active focus. Once the user cancels, the framework returns an error code—specifically LAError.userCancel or LAError.systemCancel.

    Our logging revealed that upon receiving this cancellation error, the app posted a notification to update the view model’s state, signaling that the biometric process was no longer in progress. Because SwiftUI is highly reactive, updating this state triggered a view re-evaluation. Unfortunately, the logic dictating when to invoke the authentication method lacked a strict gating mechanism, inadvertently re-triggering the LAContext evaluation before the previous cancellation was fully processed by the UI thread.

    WHAT WENT WRONG: WHY DID THE PASSCODE CANCELLATION TRIGGER A PHANTOM PROMPT?

    By analyzing the system logs, we traced the exact sequence of events that led to the phantom prompt and the orphaned callback. The failure stemmed from a combination of aggressive context invalidation and reactive state loops.

    • Aggressive Context Invalidation: Upon receiving a cancellation error, our error handling block executed a reset method that called context.invalidate() and immediately instantiated a new LAContext.
    • Reactive Redraws: Simultaneously, a Combine publisher broadcasted that the biometric flow was finished. The view model updated its state on the main thread, causing SwiftUI to redraw the view.
    • Orphaned Callbacks: The view redraw mistakenly satisfied the conditions to launch biometric authentication again. It utilized the freshly created LAContext. When the user successfully authenticated on this second prompt, the closure executed. However, the SwiftUI view had already detached from the original lifecycle expectation and the higher-level completion handler responsible for routing the user to the dashboard was lost in memory.

    HOW WE APPROACHED THE SOLUTION: WHAT STRATEGIES DID WE EVALUATE?

    When you hire software developer teams to build resilient architectures, the first step is analyzing all available paths rather than applying a quick patch. We explored several approaches to stabilize the authentication flow.

    DID WE CONSIDER DELAYING STATE UPDATES TO PREVENT SWIFTUI REDRAWS?

    Our first thought was to debounce or delay the state update that triggered the view redraw. By wrapping the state change in an asynchronous delay, we could give the OS enough time to dismiss the passcode view completely. While this reduced the frequency of the phantom prompt, it was a race condition workaround, not a deterministic solution. Relying on arbitrary time delays in production mobile applications often leads to fragmented behavior across different device models and OS versions.

    COULD WE RELY SOLELY ON LAERROR CODES FOR STATE MANAGEMENT?

    We analyzed the possibility of heavily branching our logic based on every specific LAError code. We already tracked userCancel, appCancel and systemCancel. The idea was to prevent any state changes specifically on user cancellation. However, this broke the app’s ability to gracefully fall back to alternative manual login screens. The view needed to know the authentication failed, regardless of the specific error code, to update the UI appropriately.

    WHAT ABOUT DECOUPLING LACONTEXT FROM THE VIEW LIFECYCLE?

    The most robust strategy involved fully decoupling the LAContext evaluation from SwiftUI’s reactive redraws. Instead of allowing view modifiers like .onAppear or reactive state bindings to trigger the biometric prompt, we moved the invocation behind a strict state machine managed exclusively by an isolated service layer. We also realized we needed a locking mechanism to prevent re-entry.

    FINAL IMPLEMENTATION: HOW DID WE STABILIZE THE LOCALAUTHENTICATION FLOW?

    The definitive fix required a combination of an internal lock to prevent concurrent authentication requests, careful closure memory management and deferring context invalidation. Organizations that hire Swift developers for secure mobile platforms expect this level of strict concurrency control.

    Here is the sanitized, generic version of the solution we implemented:

    final class BiometricAuthenticationService {
        private var context = LAContext()
        private var isAuthenticating = false
        
        func authenticateUser(reason: String, completion: @escaping (Result<Void, Error>) -> Void) {
            // 1. Prevent re-entry using a state lock
            guard !isAuthenticating else {
                return
            }
            
            isAuthenticating = true
            var evaluationError: NSError?
            
            // 2. Ensure policy can be evaluated before prompting
            guard context.canEvaluatePolicy(.deviceOwnerAuthentication, error: &evaluationError) else {
                isAuthenticating = false
                completion(.failure(evaluationError ?? CustomAuthError.unavailable))
                return
            }
            
            // 3. Evaluate the policy
            context.evaluatePolicy(.deviceOwnerAuthentication, localizedReason: reason) { [weak self] success, error in
                DispatchQueue.main.async {
                    // 4. Release the lock immediately on the main thread
                    self?.isAuthenticating = false
                    
                    if success {
                        completion(.success(()))
                    } else {
                        if let laError = error as? LAError {
                            self?.handleAuthenticationError(laError)
                        }
                        completion(.failure(error ?? CustomAuthError.unknown))
                    }
                }
            }
        }
        
        private func handleAuthenticationError(_ error: LAError) {
            switch error.code {
            case .userCancel, .systemCancel, .appCancel:
                // Do NOT immediately invalidate context here if UI is transitioning
                // Notify UI layer to handle cancellation gracefully
                AnalyticsService.log("User cancelled biometric flow")
            default:
                AnalyticsService.log("Biometric error: (error.localizedDescription)")
            }
        }
        
        func resetContext() {
            // Only invalidate when explicitly tearing down the service, not during transitions
            guard !isAuthenticating else { return }
            context.invalidate()
            context = LAContext()
        }
    }
    

    By enforcing the isAuthenticating flag, we guaranteed that even if SwiftUI triggered a view redraw, the biometric service would ignore subsequent requests until the current evaluation completely finalized and executed its completion block. Furthermore, we stopped calling context.invalidate() immediately upon user cancellation, allowing the OS to tear down the prompt naturally.

    LESSONS FOR ENGINEERING TEAMS: HOW CAN YOU AVOID SWIFTUI AND LACONTEXT CONFLICTS?

    Complex integrations between declarative UI frameworks and imperative OS frameworks often lead to subtle bugs. For teams looking to hire dedicated mobile developers, ensuring candidates understand these intersection points is vital. Here are the core takeaways:

    • Enforce Re-entry Guards: Always wrap asynchronous OS-level prompt calls (like LocalAuthentication, App Tracking Transparency or Location Permissions) in a boolean lock (e.g., isAuthenticating) to prevent overlapping requests.
    • Avoid View-Bound Invocation: Do not tie authentication triggers directly to SwiftUI view state changes that might fire multiple times. Use explicit user intents or decoupled routing logic.
    • Manage LAContext Carefully: Do not aggressively invalidate LAContext mid-transition. Let the system manage the teardown of the authentication dialog. Invalidate only during complete user session resets or distinct lifecycle events.
    • Ensure Main Thread Dispatch: Always route the results of evaluatePolicy back to the main thread before altering any state that drives the UI, preventing race conditions in view updates.
    • Trace Callback Ownership: If a callback fails to execute, check if the parent class or closure was deallocated. In reactive architectures, views are destroyed and recreated rapidly, easily causing orphaned closures if not managed properly.

    WRAP UP: WHAT IS THE ULTIMATE TAKEAWAY FOR IOS DEVELOPMENT?

    Intermittent bugs are notoriously difficult to track down, but they almost always point to race conditions between system states and application states. By implementing a strict gating mechanism and decoupling the LocalAuthentication context from SwiftUI’s reactive loops, we eliminated the phantom Face ID prompts and ensured consistent, reliable completion callbacks. If you are looking to scale your engineering capabilities with professionals who understand deep architectural stability, feel free to contact us.

    Social Hashtags

    #SwiftUI #FaceID #iOSDevelopment #Swift #iOS #AppleDeveloper #BiometricAuthentication #LocalAuthentication #MobileAppDevelopment #AppSecurity #FinTech #MobileSecurity #SwiftDeveloper #SoftwareEngineering #HireiOSDevelopers

    Frequently Asked Questions

    Trusted by businesses building and scaling software products.

    Since 1999

    3,500+ Projects Delivered

    US Based Accountability

    Selected clients across our delivery history