swiftswiftuiswiftui-navigationlinkswiftui-navigationstack

SwiftUI Navigation Issue: Unable to Reset to Welcome Screen on Logout with Nested NavigationLinks


I'm building a SwiftUI app with Firebase Authentication and experiencing navigation issues when users log out. My app has the following structure:

A root view in App.swift that conditionally shows: WelcomeView if not authenticated MainTabView if authenticated

From MainTabView, users can navigate through multiple nested NavigationLinks:

MainTabView → Settings (via NavigationLink) Settings → Account Info (via NavigationLink or sheet)

Account Info contains a Logout button When the user logs out from the deeply nested Account Info screen, Firebase Authentication state updates correctly (confirmed by print statements), but the UI doesn't navigate back to the WelcomeView.

Implementation Details Using Firebase Auth for authentication

What I've Tried Explicitly setting isAuthenticated = false in the signOut method

Using @EnvironmentObject for FireAuthManager

Trying to manually pop to root (which doesn't work well in SwiftUI)

Question What's the proper pattern in SwiftUI to reset navigation and return to the welcome screen on logout when using deeply nested NavigationLinks? How can I ensure the UI responds correctly to authentication state changes regardless of how deep in the navigation stack the user is?

func signOut(comp: (Error?) -> Void) {
    do {
        try Auth.auth().signOut()
        isProfileCompleted = nil
        self.isAuthenticated = false
        PresenceManager.shared.setOfflineOnLogout()
        comp(nil)
        print("User signed out successfully")
    } catch let signOutError as NSError {
        print("Error signing out: \(signOutError.localizedDescription)")
        comp(signOutError)
    }
}


NavigationStack {
            Group {
                if authManager.isAuthenticated == false {
                    WelcomeView()
                } else {
                        MainTabView()
                    }
                }
            }
        }

Solution

  • It should go with NavigationLink, if I understand your question correctly. The proper pattern in SwiftUI to reset navigation and return to the welcome screen on logout when using deeply nested NavigationLink is to manage a NavigationPath.

    With NavigationPath, we can use removeLast() to clear the entire stack. If possible, could you share how you are currently managing navigation in your code with NavigationPath?