skuenstler skuenstler - 1 month ago 17
iOS Question

Alert not working due to presentViewController

Seems that calling an Alert in my UIViewController causes ploblems with the presentViewController (...due to probably inadvertently trying to present the same view controller twice in quick succession...).

What could I do against that issue (...see code below) ???

Error message :

<MyApp.MyViewController: 0x67544325620> which is already presenting (null)


The code :

func textFieldShouldEndEditing(textField: UITextField) -> Bool {

if (textField.text.lengthOfBytesUsingEncoding(NSUTF8StringEncoding) > 5) {

var alert = UIAlertController(title: "Warning", message: "Only Initials with maximal 5 letters allowed!", preferredStyle: UIAlertControllerStyle.Alert)
alert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.Default, handler: nil))

// that is where the problem seems to occur.... !!! Why ????
self.presentViewController(alert, animated: true, completion: nil)

return false
}
return true
}

Answer

Do not use this code exactly, please modify to fit your situation. This is an example which may help you gain understanding and prevent your problem:

    var alert = UIAlertController(title: "Warning", message: "Only Initials with maximal 5 letters allowed!", preferredStyle: UIAlertControllerStyle.Alert)
    alert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.Default, handler: nil))

    // assuming that this is the first time your controller is presented

    println("is presenting \(presentedViewController)") //is nil

    presentViewController(alert, animated: true, completion: nil)

    //is now not nil
    println("is presenting \(presentedViewController)")        

    //something bad happened and your application is trying to present the alert again, safe guard against presenting it twice by checking if presentedViewController is nil or not
    if presentedViewController == nil {
        presentViewController(alert, animated: true, completion: nil)
    }