0

I have an iOS Objective-C application in which I am attempting to show a UIAlertController, from a UIViewController which is in the process of closing. I have tried adding this common workaround in AppDelegate:

- (UIViewController *)currentTopViewController
{
   UIViewController *topVC = [[[[UIApplication sharedApplication] delegate] window] rootViewController];
   while (topVC.presentedViewController)
   {
     topVC = topVC.presentedViewController;
   }
  return topVC;
}

Called with:

[appDelegate.currentTopViewController presentViewController:alert animated:YES completion:nil];

However this error is still appearing:

Warning: Attempt to present UIAlertController on MyViewController whose view is not in the window hierarchy!

Can anyone advise?

Chirag Kothiya
  • 955
  • 5
  • 12
  • 28
user2181948
  • 1,646
  • 3
  • 33
  • 60
  • You should send a notification (or use delegation, etc.) to the parent viewcontroller and present it from there – nathan Jul 27 '17 at 23:11
  • @nathan Could you provide an example of using a notification? – user2181948 Jul 27 '17 at 23:35
  • Example of delegation: https://stackoverflow.com/a/33229483/2124535, NotificationCenter example: https://stackoverflow.com/a/29738348/2124535 – nathan Jul 27 '17 at 23:47

2 Answers2

0

If you want to display an alert upon closing a viewcontroller, then you can just implement dismiss with completion block and display it there. For example:

[self dismissViewControllerAnimated:YES completion:^(void) {
  // UIAlertController code here

}];
GeneCode
  • 7,545
  • 8
  • 50
  • 85
0

You can use UIWindow with a transparent UIViewController and then presenting the UIAlertController on it. Below link provides a category on UIAlertController that has a show method in Objective-C. You can use it.

Link: How to present UIAlertController when not in a view controller?

Glorfindel
  • 21,988
  • 13
  • 81
  • 109
Asif Raza
  • 836
  • 12
  • 29