Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UIAlertController Not Working with Swift 3.0

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.

like image 767
BlackHatSamurai Avatar asked Oct 15 '16 05:10

BlackHatSamurai


2 Answers

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.

like image 167
Nirav D Avatar answered Sep 20 '22 22:09

Nirav D


 let actionSheetController: UIAlertController = UIAlertController(title: "Action Sheet", message: "Swiftly Now! Choose an option!", preferredStyle: .alert)
 let cancelAction: UIAlertAction = UIAlertAction(title: "Cancel", style: .cancel) { action -> Void in
            //Just dismiss the action sheet
        }
 actionSheetController.addAction(cancelAction)
 self.present(actionSheetController, animated: true, completion: nil)
like image 22
Himanshu Moradiya Avatar answered Sep 19 '22 22:09

Himanshu Moradiya