Login / Logout Flow: SwiftUI and EnvironmentObject
EnvironmentObject is useful when you want to create a dependency in a higher component of the layout tree and use it on a lower component without having to pass it down the tree through every child component.
We will now use EnvironmentObject to monitor when a user logs in and out.
- When the user is successfully logged in (isLoggedIn = true), they are directed to the rest of the application views.
- When a user is logged out (isLoggedIn = false) at any point within the app, they are directed to the login page.
We need the following components:
- User State View Model
- Application Switcher
- Login Screen
- Home Screen (Our Application Views)
User State View Model
The user state view model tracks and broadcasts the user status. We store this view model in an EnvironmentObject.
We make our view model instance available (Line 14) to all child views, starting from the ApplicationSwitcher view
The Login screen uses the UserStateViewModel to invoke signIn
Home Screen with Logout Button
The Home screen uses the UserStateViewModel to invoke signOut
At all times the Application Switcher is monitoring the isLoggedIn status: