Tracking down a "Application tried to present modally an active controller" error

I have an app that's live and it's experiencing a very small number of crashes. The crashes are throwing an NSInvalidArgumentException with the message "Application tried to present modally an active controller <UIAlertController: 0x122867800>."

I use a UIAlertController in a few places, but they all fit the same usage pattern below where self is a UIViewController:

Code Block obj-c
UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"..." message:@"..." preferredStyle:UIAlertControllerStyleAlert];
[self presentViewController:alert animated:YES completion:nil];


After spending a lot of time looking through the code, debugging, and looking for others with the same issue, I guess I have 2 questions:
  1. What I *think* this error message is trying to tell me is that I'm trying to present the same active view controller instance on itself -- that I have a pointer to a view controller, it's already displayed modally, and I'm trying to display the same view controller again. In this scenario that's not true. Is there something I'm not understanding about the error message? Is it trying to tell me something different?

  2. The exception traces don't contain much helpful information and I haven't been able to reproduce this on a device or simulator. Does anyone have advice for tracking down this sort of exception?

I do have scenarios where a view controller is presented modally, and it could present a UIAlertController, so I thought there might be some sort of race condition where the alert was trying to be displayed before the view controller was ready, but I haven't been able to force that to happen in local testing, either.

Any thoughts or feedback on this are appreciated! Thanks!
You should show more of real code to get a sure diagnostic.

But probably, self should not be the one to present the alert at the place where you try.

Maybe you need to get the topMost controller and call present from it:

Code Block
func getTopMostViewController() -> UIViewController? {
        var topMostViewController = UIApplication.shared.keyWindow?.rootViewController
        while let presentedViewController = topMostViewController?.presentedViewController {
            topMostViewController = presentedViewController
        }
        return topMostViewController
    }

Tracking down a "Application tried to present modally an active controller" error
 
 
Q