Home > Software engineering >  How to instantiate view controller from GIDSignIn method in AppDelegate?
How to instantiate view controller from GIDSignIn method in AppDelegate?

Time:10-04

I have my Google Sign In methods within my AppDelegate. Once a user is authenticated with Google, I would like them to be brought from the sign-in page to the homepage. Here's the relevant code in my AppDelegate:

var window: UIWindow?

func sign(_ signIn: GIDSignIn!, didSignInFor user: GIDGoogleUser!, withError error: Error!) {
        print("User Email: \(user.profile.email ?? "No Email")")
        
        // I use this same code in multiple view controllers to instantiate the homepage
        let mainStoryboard:UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
        let homePage = mainStoryboard.instantiateViewController(identifier: Constants.Storyboard.tabBarController)
        self.window?.rootViewController = homePage
        self.window?.makeKeyAndVisible() 
    }

My print() statement gets called and the app doesn't crash. But the user just stays in the sign-in page after they're authenticated. What could I be missing to instantiate the homepage?

Any help is much appreciated!

CodePudding user response:

Replace instantiateViewController(identifier) with instantiateViewController(with identifier) like this

var window: UIWindow?

func sign(_ signIn: GIDSignIn!, didSignInFor user: GIDGoogleUser!, withError error: Error!) {
        print("User Email: \(user.profile.email ?? "No Email")")
        
        
        let mainStoryboard:UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
        let homePage = mainStoryboard.instantiateViewController(withIdentifier: Constants.Storyboard.tabBarController)
        self.window?.rootViewController = homePage
        self.window?.makeKeyAndVisible() 
    }

CodePudding user response:

This was solved when I deleted my SceneDelegate and removed the Application Scene Manifest from info.plist. Steps can be found here.

This is the code in my AppDelegate:

func sign(_ signIn: GIDSignIn!, didSignInFor user: GIDGoogleUser!, withError error: Error!) {
        
        if error == nil {
            print("User Email: \(user.profile.email ?? "No Email")")
            
            let mainStoryboard:UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
            let homeViewController = mainStoryboard.instantiateViewController(withIdentifier: Constants.Storyboard.tabBarController)
            self.window = UIWindow(frame: UIScreen.main.bounds)
            self.window?.rootViewController = homeViewController
            self.window?.makeKeyAndVisible()
        }
    }
  • Related