Photo by Florian Berger on Unsplash

Firebase Email/Password Authentication: SwiftUI

Paul Allies

--

Firebase Authentication provides an easy-to-use SDK to authenticate users. Most apps need to know the identity of a user. Knowing a user’s identity allows an app to securely save user data in the cloud and provide the same personalized experience across all of the user’s devices.

Here we’ll show how to use Firebase Authentication to authenticate users with email and password.

Setup

  1. Log into your firebase console.
  2. Create a firebase project,
  3. Navigate to Authentication
  4. Enable the Email/password Sign-In Provider

5. Add a User

6. Add an iOS application by providing the app bundle name and downloading the Google-Service-info.plist file

With this plist file, you are now ready to configure your application for FB auth

Drag and drop the file into your XCode project

Next, install Firebase Core and Firebase Auth using Swift Package Manager (SPM).

To install Firebase using SPM, go to File → Add Packages… Enter the following URL. Select Firebase Auth at the end.

https://github.com/firebase/firebase-ios-sdk.git

Login View Model

Using MVVM, Let’s first work on the view model of our login screen.

I’m using a User type to store user information. I initialize the view model by registering an Auth state listener. On login and logout, the auth state is changed and the listener callback is fired. At this point, the “currentUser” variable is updated. The view model has an “isLoggedIn” variable which is also updated accordingly.

Login View

Now let’s code up the Login view which observes and reacts to this view model

When the user is successfully authenticated, information is shown with a logout button. Auth Errors are displayed using an alert

--

--