UIAlertController Not Working with Swift 3.0

BlackHatSamurai picture BlackHatSamurai · Oct 15, 2016 · Viewed 31.5k times · Source

I have the following alert method.

static func notifyUser(_ title: String, message: String) -> Void
{
    let alert = UIAlertController(title: title,
                                  message: message,
                                  preferredStyle: UIAlertControllerStyle.alert)

    let cancelAction = UIAlertAction(title: "OK",
                                     style: .cancel, handler: nil)

    alert.addAction(cancelAction)
    self.presentViewController(alert, animated: true, completion: nil)
}

I get an error saying that there is an extra argument animated in the presentViewController method, but when I take it out, it still doesn't dismiss the error, and then I'm told that completion is an extra argument.

Answer

Nirav D picture Nirav D · Oct 15, 2016

presentViewController is changed in Swift 3 like this.

present(alert, animated: true)

Check Apple Documentation for more details.

From Swift 3 completionis optional so if you doesn't want handle the completion block no need to write nil for that and if you want to handle completion block then write like this.

self.present(alert, animated: true) { 

}

Note: Your notifyUser method is declared with static so you cannot use self with it so remove that also to remove the next error that you get after correcting this one.