frzi / swiftui-router

Path-based routing in SwiftUI
MIT License
900 stars 43 forks source link

Set path on app launch #33

Closed denizdogan closed 2 years ago

denizdogan commented 2 years ago

What's the proper way to set the navigation path on app launch, e.g. based on whether the user is logged in to some API?

frzi commented 2 years ago

There is no definitive "best way". It all depends on how you implement your logic of users logging in and authenticating etc.

Router can be given an initialPath. If you can figure out whether a user is logged in directly once the app launches, something like this could work:

@main
struct MyApp: App {
    @StateObject private var userData = UserData()

    private var initialPath: String {
        userData.isLoggedIn ? "/user" : "/"
    }

    var body: some Scene {
        WindowGroup {
            Router(initialPath: initialPath) {
                ContentView()
            }
        }
    }
}

Or if it's an asynchronous task, you could programmatically navigate to specific path:

@main
struct MyApp: App {
    @StateObject private var userData = UserData()

    var body: some Scene {
        WindowGroup {
            Router {
                ContentView()
            }
            .environmentObject(userData)
        }
    }
}

struct ContentView: View {
    @EnvironmentObject private var userData: UserData
    @EnvironmentObject private var navigator: Navigator
    @State private var isBusy = true

    private func checkLogin() {
        userData.authorizeUser { success in
            self.isBusy = false
            if success {
                navigator.navigate(to: "user")
            }
        }
    }

    var body: some View {
        Group {
            if !isBusy {
                SwitchRoutes {
                    Route(path: "user", content: UserView())
                    Route(content: HomeView())
                }
            }
            else {
                ProgressView()
            }
        }
        .onAppear(perform: checkLogin)
    }
}

These are very rough and simplistic examples. But it does demonstrate multiple ways to tackle the challenge.

denizdogan commented 2 years ago

Thanks, looks good!