iosuialertcontroller

How to present UIAlertController when not in a view controller?


Scenario: The user taps on a button on a view controller. The view controller is the topmost (obviously) in the navigation stack. The tap invokes a utility class method called on another class. A bad thing happens there and I want to display an alert right there before control returns to the view controller.

+ (void)myUtilityMethod {
    // do stuff
    // something bad happened, display an alert.
}

This was possible with UIAlertView (but perhaps not quite proper).

In this case, how do you present a UIAlertController, right there in myUtilityMethod?


Solution

  • I posted a similar question a couple months ago and think I've finally solved the problem. Follow the link at the bottom of my post if you just want to see the code.

    The solution is to use an additional UIWindow.

    When you want to display your UIAlertController:

    1. Make your window the key and visible window (window.makeKeyAndVisible())
    2. Just use a plain UIViewController instance as the rootViewController of the new window. (window.rootViewController = UIViewController())
    3. Present your UIAlertController on your window's rootViewController

    A couple things to note:

    Lastly, I have a completed implementation if you just want to look at that.

    https://github.com/dbettermann/DBAlertController