-3

I have been battling to get this to work. I have written a function to try and check if the user is logged in or not and if they are not they will be presented with a login screen but I keep getting an error that the Attempt to present....whose view is not in the window hierarchy! and it displays the default storyboard, here is the code below

func checkuser () {
    let currentUser = FIRAuth.auth()?.currentUser
    if currentUser != nil {
        self.view.window?.rootViewController = storyboard?.instantiateViewController(withIdentifier: "eventsstoryboard")
        print("user logged in")
    }   
    else
    {

        let vc = storyboard?.instantiateViewController(withIdentifier: "loginvc") as! loginviewcontroller
        self.present(vc,animated: true, completion: nil)
        print("user not logged in")

    }
}
checkuser()
Arasuvel
  • 2,971
  • 1
  • 25
  • 40
  • 2
    from where you are calling the function checkuser? – Van Jan 23 '18 at 07:40
  • refer the answer to the question below [StackOverFlow Question](https://stackoverflow.com/questions/11862883/attempt-to-present-uiviewcontroller-on-uiviewcontroller-whose-view-is-not-in-the) – Akhil Jan 23 '18 at 07:48
  • 3
    Possible duplicate of [Attempt to present UIViewController on UIViewController whose view is not in the window hierarchy](https://stackoverflow.com/questions/11862883/attempt-to-present-uiviewcontroller-on-uiviewcontroller-whose-view-is-not-in-the) – Milan Nosáľ Jan 23 '18 at 08:28
  • if you're trying this while the view is loading, you should move it to viewDidAppear – Russell Jan 23 '18 at 08:39
  • im am calling the function in the viewdidload section – Rati Robson Kaydee Jan 23 '18 at 11:35

2 Answers2

0

check your if-part, are you presenting your viewController as:

let vc = storyboard?.instantiateViewController(withIdentifier: "eventsstoryboard") as! someviewcontroller
self.present(vc,animated: true, completion: nil)
print("user logged in")
Madhur
  • 1,056
  • 9
  • 14
0

thanks all got it working using the below method. used viewdidappear and it solved it

override func viewDidAppear(_ animated: Bool) {
    super.viewDidAppear(true)

    func checkuser () {
        let currentUser = FIRAuth.auth()?.currentUser
        if currentUser != nil
        {
            self.view.window?.rootViewController = storyboard?.instantiateViewController(withIdentifier: "eventsstoryboard")
            print("user logged in")
        }

        else
        {

            let vc = storyboard?.instantiateViewController(withIdentifier: "loginvc") as! loginviewcontroller
            self.present(vc,animated: true, completion: nil)
            print("user not logged in")

        }
    }
    checkuser()

}