Nick Turner
Nick Turner

Reputation: 989

Finding the current view controller active

I have a Login storyboard that I instantiate whenever the user logs in. I have a main storyboard that is the actual application.

When my application is set to inactive ( closing the app ) and then re-activated ( opening the app again ) the AppDelegate checks to see if the 2 minute timeout has occurred. If so I want to show an alert that it has timed out and this works great.

The problem I have is that if you're on the Login screen I don't want to show the message. Since my Storyboard uses a TabBarController, I don't have a valid navigation controller. How do I determine if the LoginViewController is currently being shown from the App Delegate? How do I get the top most View controller's class name?

NavigationController is null, fyi

Upvotes: 0

Views: 6377

Answers (1)

BigDan
BigDan

Reputation: 176

First, you need to have a reference to the UITabBarController. This is very easy if it's set as your Initial View Controller in IB. You can check this by opening your storyboard and looking for a little grey arrow to the left of your UITabBarController. If so, then simply do this:

UITabBarController *myTabBarController;
if ([_window.rootViewController isKindOfClass:[UITabBarController class]]) {

    NSLog(@"This window's rootViewController is of the UITabBarController class");

    myTabBarController = (UITabBarController *)_window.rootViewController;

}

If you are using UITabBarController, you can get references to its child UIViewControllers via:

[myTabBarController objectAtIndex:index];

You can also query your TabBarController directly:

NSLog(@"Selected view controller class type: %@, selected index: %d", [myTabBarController selectedViewController], [myTabBarController selectedIndex]);

The zero-based indexing scheme follows the order of the tabs as you've set them up, whether programmatically or through IB (leftmost tab = index 0).

Once you have the reference to your UITabBarController, the rest is pretty easy:

LoginViewController* myLoginViewController;

if(![[myTabBarController selectedViewController] isKindOfClass:[LoginViewController class]){
    //If the currently selected ViewController is NOT the login page
    //Show timeout alert
}

Upvotes: 1

Related Questions