SwiftUI - Delaying screen to avoid flicker for logged in users

Viewed 119

I'm using Firebase for authentication in my app. See below for code. Currently, because of how my app loads, if a user is already logged in, then what ends up happening is that they see a flicker of the SignUpView() before going to the AppMainView. I'm guessing this is because it takes time for session to load and register that the user is logged in already. How can I avoid this flicker? Thanks!

struct ContentView: View {
    @EnvironmentObject var session: SessionStore

    var body: some View {
        Group {
            if (session.session != nil) {
                AppMainView()
            } else {
                SignUpView()

            }
        }
        .onAppear(perform: getUser)
    }
}
1 Answers

You can introduce a loggedIn property in your ObservableObject object:

class SessionStore: ObservableObject {
    @Published var loggedIn: Bool? = nil
    ...
}

and present views basing on the value of the loggedIn variable:

struct ContentView: View {
    @EnvironmentObject var session: SessionStore

    var body: some View {
        content
            .onAppear(perform: getUser)
    }

    var content: AnyView {
        switch session.loggedIn {
        case true:
            // User is loggeed in
            return AnyView(AppMainView())
        case false:
            // User is not loggeed in
            return AnyView(SignUpView())
        default:
            // Session not loaded
            return AnyView(LoadingView())
        }
    }
}

Lastly, in the SessionStore you need to set loggedIn when the store finishes loading.

Related