iOS viewWillAppear Error: "view is not in the window hierarchy"

544 Views Asked by At

I have a Swift application, and what I'd like to do is that every time the app becomes active, I'd like to check for a user in session. If not found, I'd like to show a login view controller that I designed in my Storyboard. If found, I need everything to just resume as usual.

I have another home view controller, which is set to be my initial view controller. I don't want the home view controller to show up if a user is not found.

I am doing this to deal with state restoration while also looking for user in session:

func application(application: UIApplication, shouldRestoreApplicationState coder: NSCoder) -> Bool {
    return <userInSession> != nil
}

I created a segue from home view controller to login view controller. In the home view controller's viewDidAppear method, I check to make sure the user is signed in. If they aren't signed in, I perform the segue to the login view controller.

Once a user logs in you I just dimiss the login view controller.

The issue is that because I use viewDidAppear, the home view controller is seen for a split second before the login view controller shows up in case the user is not logged in. I want to avoid that. I tried using the viewWillAppear method, but that produces the following error:

2014-12-14 23:42:52.910 appname[78187:18685210] Warning: Attempt to present < appname.LoginUIViewController: 0x7fdcc1616970> on < appname.HomeUITabBarViewController: 0x7fdcc1746610> whose view is not in the window hierarchy!

Any thoughts on how to handle the situation?

1

There are 1 best solutions below

0
On

I don't think you can avoid showing the home view first, the way you have it set up. (I have seen the problem you are describing when a view in a flow needed to be bypassed in certain cases.)

Try rearranging your storyboard so that the login view controller is first, and segues to the home view controller.

When a user first runs the app, he/she will need to log in first. Upon successful login, user goes to home view controller and beyond.

When app closes, save app state by returning YES in shouldSaveApplicationState. When app restarts, shouldRestoreApplicationState is called. There you check if user is logged in, and return NO if not, so that state is not restored. This should force user to beginning of app, i.e. your login view.