12.4. Authentication State Handler
Now, it's time to set up the authentication for the app. We will use the right navigation bar buttons to manage the sign-in, register, and logout operations. Before we set up those buttons, let's write the logic to handle the authentication states in the app. Let's open ViewCOntroller.swift file and write the following code there:
//
// ViewController.swift
// App12
//
// Created by Sakib Miazi on 6/1/23.
//
import UIKit
import FirebaseAuth
class ViewController: UIViewController {
//codes omitted...
var handleAuth: AuthStateDidChangeListenerHandle?
var currentUser:FirebaseAuth.User?
override func loadView() {
view = mainScreen
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
//MARK: handling if the Authentication state is changed (sign in, sign out, register)...
handleAuth = Auth.auth().addStateDidChangeListener{ auth, user in
if user == nil{
//MARK: not signed in...
}else{
//MARK: the user is signed in...
}
}
}
override func viewDidLoad() {
super.viewDidLoad()
//codes omitted...
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
Auth.auth().removeStateDidChangeListener(handleAuth!)
}
}In the above code:
On line 15, we create an authentication state change listener called
handleAuth. We will use this listener to track whether any user is signed in.On line 16, we create a variable to keep an instance of the current signed-in Firebase user.
Now, you can see that we are overriding two methods that we did not use before.
viewWillAppear: is a lifecycle method where you can handle the logic before the screen is loaded.viewWillDisappear: is another lifecycle method where you can handle the logic right before the screen disappears.
In
viewWillAppearmethod, we definehandleAuthhandler with a closure to handle the authentication state changes. This closure will be automatically called every time a user signs in or logs out. In the closure, you see that we have two parameters:auth, anduser. If the user is nil, there is no authenticated user; else, there is a signed-in user in the app.In
viewWillDisappearmethod, we remove the listener from the app so that we do not run the listener infinitely.
if user == nil
If the user is nil, meaning there is no signed-in user, we will write the following logic:
In the above code,
We hide and disable the floating add contact button because if there is no signed-in user, there is no point in having the option to add a contact.
Then we also need to clear the local array for contacts by removing all the array elements.
Then finally, we reload the table view to reflect the authentication state change.
else (the user is logged in)
To handle if the user is signed in, we write logic inside the else closure:
Here we update the local currentUser instance with the signed-in user. We then update the label to display the signed-in user's name and enable and display the floating add contact button.
Last updated
Was this helpful?