Sulochana Fernando
Sulochana Fernando

Reputation: 21

Firebase Authentication using swift

I'm trying to implement a login feature in my Swift app using Firebase Authentication. How can I check if a user is already logged in and redirect them to the home screen if they are?

I followed the Firebase Authentication documentation and was able to successfully set up my login flow with email and password. However, when a user opens the app and has already logged in previously, I want to check if they are already authenticated and automatically redirect them to the home screen. To do this, I tried using the addStateDidChangeListener method to listen for changes in the user's authentication state, but I'm not sure how to use this information to automatically redirect the user. I was expecting that if the user was already logged in, the listener would detect this and trigger a redirection to the home screen

Upvotes: 1

Views: 60

Answers (2)

landandev
landandev

Reputation: 3

If you use the ContentView as the primary entry point, you can perform a verification by checking if the user is currently authenticated here. This can be achieved by accessing the current user through your authViewModel or the Firebase module depending on your implementation. Here is a example with viewModel:

import SwiftUI
import FirebaseAnalytics
import Firebase

struct ContentView: View {
    @EnvironmentObject var authViewModel: AuthViewModel
    var body: some View {
        Group{
            if authViewModel.userSession != nil {
                ListView()
            }else{
                LoginView()
            }
        }
    }
}

Upvotes: 0

udi
udi

Reputation: 3853

In your viewcontroller u can check like this.

    if Auth.auth().currentUser != nil {
        // User is already authenticated, redirect to home screen
        // Redirect them to home screen

    }else{
        //user not logged in
        //show login view
    }

Upvotes: 1

Related Questions