Photo by James Wheeler from Pexels

Login / Logout Flow: SwiftUI and EnvironmentObject

Paul Allies
2 min readNov 8, 2021

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.

  1. When the user is successfully logged in (isLoggedIn = true), they are directed to the rest of the application views.
  2. When a user is logged out (isLoggedIn = false) at any point within the app, they are directed to the login page.
Flow

We need the following components:

  1. User State View Model
  2. Application Switcher
  3. Login Screen
  4. 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

Application Switcher

Login Screen

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:

--

--