UIAlertController won't display - In Swift
The problem is that by the time you call this following function:
present(alertController, animated: true, completion: nil)
your mail view controller is still visible. You have to make sure that the alertController
is presented on the top of window hierarchy. In your example, you have the following window hierarchy:
+---------------------------+
| MailComposeViewController |
+---------------------------+
||
+---------------------------+
| ContactUsViewController |
+---------------------------+
What you should do instead is to dismiss the email view controller first. When that is done, show you alert view controller.
let alertController = UIAlertController(title: "test", message: "test", preferredStyle: .Alert)
let okButton = UIAlertAction(title: "Okay", style: .Default, handler: nil)
alertController.addAction(okButton)
controller.dismissViewControllerAnimated(true){ () -> Void in
self.present(alertController, animated: true, completion: nil)
}
Alternatively, you can also present your alertController
on top of the MailComposeViewController
, like so:
let alertController = UIAlertController(title: "test", message: "test", preferredStyle: .Alert)
let okButton = UIAlertAction(title: "Okay", style: .Default, handler: nil)
alertController.addAction(okButton)
controller.present(alertController, animated: true, completion: nil)
I needed an actionSheet rather than an alert, and due to my specific circumstances, none of the solutions here worked. If your UIAlertController isn't showing, an alternative way to do this is to always put it as the topmost window (in Swift 4):
func topmostController() -> UIViewController? {
if var topController = UIApplication.shared.keyWindow?.rootViewController {
while let presentedViewController = topController.presentedViewController {
topController = presentedViewController
}
return topController
}
return nil
}
// Now put up the menu
let menu=UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet)
menu.addAction(UIAlertAction(title: "Test", style: .default, handler: {_ in self.doTest()} ))
menu.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: {_ in self.doCancel()} ))
topmostController()?.present(menu, animated: true, completion: nil)
This displays the window regardless of your view controller stack.