Dismissal of UIAlertController (best practice)
The dismissal is "included" in the presentViewController
call. You do not need a delegate because you have the completion block. In this block you put what you would normally put into the delegate callback, except the call to dismiss the alert.
As far as "best practice" is concerned, I noted that in many APIs, Apple replaced delegate callbacks with completion blocks. Apple typically recommends using the block syntax. I surmise this could be partly because it helps keeping the related code sections together.
There is an elegant way! Just write the action or function inside the alert controller's cancel action. (here the action style should be .cancel
)
Code for Swift 3:
let Alert: UIAlertController = UIAlertController(title: nil, message: nil, preferredStyle: UIAlertControllerStyle.actionSheet)
let OkAction: UIAlertAction = UIAlertAction(title: “Ok”, style: .default) { ACTION in
//Will be called when tapping Ok
}
let CancelAction: UIAlertAction = UIAlertAction(title: "Cancel", style: .cancel) {ACTION in
// Will be called when cancel tapped or when alert dismissed.
// Write your action/function here if you want to do something after alert got dismissed”
}
Alert.addAction(OkAction)
Alert.addAction(CancelAction)
present(Alert, animated: true, completion: nil)