sean jon
sean jon

Reputation: 15

I am having a problem with checking if my users are signed in to Firebase and changing the the initial view controller

My goal is to check if my users have signed in to my app in Firebase before. Then change the initial view controller from my Navigation controller to my TabBarController. I'd like to do this for a better user experience so they don't have to log in every time.

Also where is the best place to put this code? my first View controller or my app Delegate?

if Auth.auth().currentUser != nil {
        // User is signed in.
        func transitionToTab() {

            let tabBarController =
                storyboard?.instantiateViewController(identifier: Constants.Storyboard.TabBarController) as? TabBarController

            view.window?.rootViewController = tabBarController
            view.window?.makeKeyAndVisible()

        }
    } else {
        // No user is signed in.
        func tranitionToView() {

            _ =
                storyboard?.instantiateViewController(identifier: Constants.Storyboard.HomeViewController) as? ViewController

            view.window?.makeKeyAndVisible()

  }
}

Upvotes: 0

Views: 51

Answers (2)

Harry J
Harry J

Reputation: 1966

Your problem is you don't call the functions within the if/else statement.

I would recommend creating an additional slash screen that replicates the one within launchscreen.storyboard to initiate your authentication process. Your code should look similar to this;

if Auth.auth().currentUser != nil {
            // User is signed in.
            let tabBarController =
                storyboard?.instantiateViewController(identifier: Constants.Storyboard.TabBarController) as? TabBarController

            view.window?.rootViewController = tabBarController
            view.window?.makeKeyAndVisible()
        } else {
            // No user is signed in.
            storyboard?.instantiateViewController(identifier: Constants.Storyboard.HomeViewController) as? ViewController

            view.window?.makeKeyAndVisible()
    }

Upvotes: 1

Anil Kumar
Anil Kumar

Reputation: 1984

you can use this function from app delegate method "didFinishLaunchingWithOptions" and make an userdefaults to store current user object or any check that you will true once user login into the app and in Appdelegate "didFinishLaunchingWithOptions" check if it's true than set initial page tabbarcontroller else show login screen.

Upvotes: 0

Related Questions