Here are two extension functions you can add on UIViewController
which make it easy to display alerts. One of the functions will show an alert with a single action option, and the other will show an alert with two options.
extension UIViewController {
func showAlert(title: String? = nil,
message: String,
actionTitle: String? = nil,
handler: ((UIAlertAction) -> Void)? = nil) {
let alertController = UIAlertController(title: title, message: message, preferredStyle: .alert)
let action = UIAlertAction(title: actionTitle ?? "OK", style: .default, handler: handler)
alertController.addAction(action)
self.present(alertController, animated: true, completion: nil)
}
func showDuoAlert(title: String? = nil,
message: String,
primaryActionTitle: String,
primaryActionHandler: ((UIAlertAction) -> Void)? = nil,
primaryActionStyle: UIAlertAction.Style = .default,
secondaryActionTitle: String,
secondaryActionStyle: UIAlertAction.Style = .default,
secondaryActionHandler: ((UIAlertAction) -> Void)? = nil) {
let alert = UIAlertController(title: title, message: message, preferredStyle: .alert)
alert.addAction(UIAlertAction(title: secondaryActionTitle,
style: secondaryActionStyle,
handler: secondaryActionHandler))
alert.addAction(UIAlertAction(title: primaryActionTitle,
style: primaryActionStyle,
handler: primaryActionHandler))
present(alert, animated: true, completion: nil)
}
}
Use within UIViewController
:
showAlert(message: "Error", actionTitle: "Close") { _ in
self.closeAndLogout()
}
showDuoAlert(title: "Error",
message: "There was an error with your request. What would you like to do?",
primaryActionTitle: "Close",
primaryActionHandler: { _ in self.closeAndLogout() },
secondaryActionTitle: "Go Back",
secondaryActionHandler: { _ in self.goBack() })