Swift -> Show alert with alert action callback

Alerts are very important to show general/error information to user. In swift we can display alerts using UIAlertController.

//This example is when there is no alert action required. You don’t want to capture user answer and just enable click on action items. This use case is important in conveying general information like “The sky is blue”. This is such information which does not require any reaction to action.

UIAlertController.showAlert(presenter: self, title:"my title", message:"my message", okHandler:nil)

func showAlert(presenter:AnyObject?, title:String?, message:String?, okHandler:((UIAlertAction)->Void)?) {
    let alertController = UIAlertController(title: title, message: message, preferredStyle: .alert)
    let okAction = UIAlertAction(title: "Ok", style: .default, handler:  okHandler)
    presenter?.present(alertController, animated: true, completion: nil)

//This example is when there is an action required. You want to capture user answer. For example on click of “ok” you want to print some information.

UIAlertController.showAlert(presenter: self, title: "my title", message: "my message", okHandler: { (alert) in
    print("User pressed OK")
    // TODO: Some work based on OK click.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: