Ios – Presenting a modal controller without knowing the current view controller

iosmodal-dialogpresentmodalviewcontroller

Is there a way to present a view controller modally without knowing what the visible view controller view is? Basically sort of like you would show an alert view at any points in time.

I would like to be able to do something like:

MyViewController *myVC = [[MyViewController alloc] init];
[myVC showModally];

I'd like to be able to call this from anywhere in the app, and have it appear on top. I don't want to care about what the current view controller is.

I plan to use this to show a login prompt. I don't want to use an alert view, and I also don't want to have login presentation code throughout the app.

Any thoughts on this? Or is there maybe a better way to achieve this? Should I just implement my own mechanism and just place a view on top of the window?

Best Answer

Well, you can follow the chain.

Start at [UIApplication sharedApplication].delegate.window.rootViewController.

At each view controller perform the following series of test.

If [viewController isKindOfClass:[UINavigationController class]], then proceed to [(UINavigationController *)viewController topViewController].

If [viewController isKindOfClass:[UITabBarController class]], then proceed to [(UITabBarController *)viewController selectedViewController].

If [viewController presentedViewController], then proceed to [viewController presentedViewController].