What is the best way to check if a UIAlertController is already presenting?
I have a tableview which, when loaded, each cell could possibly return an NSError, which I have chosen to display in a UIAlertController. Problem is I get this error in the console if multiple errors are returned.
Warning: Attempt to present UIAlertController: 0x14e64cb00 on MessagesMasterVC: 0x14e53d800 which is already presenting (null)
Ideally, I would ideally like to handle this in my UIAlertController extension method.
class func simpleAlertWithMessage(message: String!) -> UIAlertController {
let alertController = UIAlertController(title: nil, message: message, preferredStyle: UIAlertControllerStyle.Alert)
let cancel = UIAlertAction(title: "Ok", style: .Cancel, handler: nil)
alertController.addAction(cancel)
return alertController
}
Based on matt's answer, I changed the extension to a UIViewController extension, its much cleaner and saves lots of presentViewController code.
func showSimpleAlertWithMessage(message: String!) {
let alertController = UIAlertController(title: nil, message: message, preferredStyle: UIAlertControllerStyle.Alert)
let cancel = UIAlertAction(title: "Ok", style: .Cancel, handler: nil)
alertController.addAction(cancel)
if self.presentedViewController == nil {
self.presentViewController(alertController, animated: true, completion: nil)
}
}
Solution 1:
It is not the UIAlertController that is "already presenting", it is MessagesMasterVC. A view controller can only present one other view controller at a time. Hence the error message.
In other words, if you have told a view controller to presentViewController:...
, you cannot do that again until the presented view controller has been dismissed.
You can ask the MessagesMasterVC whether it is already presenting a view controller by examining its presentedViewController
. If not nil
, do not tell it to presentViewController:...
- it is already presenting a view controller.
Solution 2:
if ([self.navigationController.visibleViewController isKindOfClass:[UIAlertController class]]) {
// UIAlertController is presenting.Here
}