0

I would like to present a full screen ViewController without any knowledge about the current ViewController hierarchy. My current solution to find the ViewController on which I can always present my full screen ViewController is the following:

+ (UIViewController*) topMostController
{
    UIViewController *topController = [UIApplication sharedApplication].keyWindow.rootViewController;

    while (topController.presentedViewController) {
        topController = topController.presentedViewController;
    }

    return topController;
}

The background why I need this: our app uses a lot of

[[UIApplication sharedApplication]openURL:[NSURL urlWithString:@"http://www.someurl.com"]];

calls which open Safari externally. Apple started to reject this, because they think it's detrimental to the user experience, and we should use SFSafariViewController instead. But unlike openURL this requires a reference to a ViewController on which we can present SFSafariViewController. I don't want to change the code to acquire the appropriate ViewController at dozens of places, instead a universal method would be nice which gets the appropriate ViewController. The code I listed works every single time in our app, but I am unsure if it's really universal.

SPQR3
  • 647
  • 7
  • 20
  • The snippet is from here: http://stackoverflow.com/questions/6131205/iphone-how-to-find-topmost-view-controller/12684721#12684721 – SPQR3 Mar 09 '16 at 11:29
  • Have you tried navigationcontroller.visibleViewController? – Awesome.Apple Mar 09 '16 at 11:29
  • Yes, that was my first try. If I search the leaf presentedViewController on navigationController.visibleViewController it works too. But I don't want to rely UINavigationController being the rootViewController. – SPQR3 Mar 09 '16 at 11:35

0 Answers0