Search code examples
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:

    • Your UIWindow must be strongly referenced. If it's not strongly referenced it will never appear (because it is released). I recommend using a property, but I've also had success with an associated object.
    • To ensure that the window appears above everything else (including system UIAlertControllers), I set the windowLevel. (window.windowLevel = UIWindowLevelAlert + 1)

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

    https://github.com/dbettermann/DBAlertController