Mugunthan Balakrishnan Mugunthan Balakrishnan - 1 year ago 113
iOS Question

UIAlertController Error When called in a modal presented view controller in swift

I have a view controller which is modally presented and when i run UIAlertController, keep getting a error message . how can i work around this.

the alert is trigged from a button which checks a text field is empty or not.

@IBAction func registerAction(sender: AnyObject) {
alertMessage("Fields Are Empty")

func alertMessage(userMessage:String){
var myAlert = UIAlertController(title: "Alert", message: userMessage, preferredStyle: UIAlertControllerStyle.Alert)
let okAction = UIAlertAction(title: "OK", style: UIAlertActionStyle.Default, handler: nil)
self.presentViewController(myAlert, animated: true, completion: nil)

Error when i run the alert

Warning: Attempt to present <UIAlertController: 0x7f9bbb9060d0> on <AlertApp.CustomSignupVC: 0x7f9bb94accb0> which is already presenting <UIAlertController: 0x7f9bbb926660>

Answer Source

Try to add it in main operation queue.

dispatch_async(dispatch_get_main_queue()) {
    self.presentViewController(myAlert, animated: true, completion: nil)

Check this relative question : Presenting a view controller modally from an action sheet's delegate in iOS8/iOS9