Firebase Email/Password Authentication: SwiftUI
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
- Log into your firebase console.
- Create a firebase project,
- Navigate to Authentication
- 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