Why doesn't this UIAlertController show?

1.4k Views Asked by At

While attempting to implement a UI Alert I have encountered some issues. I am using swift 3.0 in Xcode 8 beta 4, I am attempting to have a button which activates a alert, one button (cancel) dismisses the alert the other (ok) performs an action as a UIAction Button would, however I have been unable to even get an alert to show.

var warning = UIAlertController(title: "warning", message: "This will erase all content", preferredStyle: .Alert)

var okAction = UIAlertAction(title: "OK", style: UIAlertActionStyle.Default) {
    UIAlertAction in
    NSLog("OK Pressed")
}

var cancelAction = UIAlertAction(title: "Cancel", style: UIAlertActionStyle.Cancel) {
    UIAlertAction in
    NSLog("Cancel Pressed")
}

warning.addAction(okAction) {
   // this is where the actions to erase the content in the strings 
}
warning.addAction(cancelAction)

self.presentViewController(warning, animated: true, completion: nil)
1

There are 1 best solutions below

1
On BEST ANSWER

That code isn't compatible with Swift 3. Things like .Alert are now .alert. And the presentViewController method is quite different.

This should work.

let warning = UIAlertController(title: "warning", message: "This will erase all content", preferredStyle: .alert)

    let okAction = UIAlertAction(title: "OK", style: UIAlertActionStyle.default) {
        UIAlertAction in
        NSLog("OK Pressed")
        //ok action should go here
    }


    let cancelAction = UIAlertAction(title: "Cancel", style: UIAlertActionStyle.cancel) {
        UIAlertAction in
        NSLog("Cancel Pressed")
    }

    warning.addAction(okAction)
    warning.addAction(cancelAction)

    present(warning, animated: true, completion: nil)

Why did you have the closure after addAction(okAction) instead of when you created the alert?

Hope this helps!