Back to blog

Displaying Alerts with UIAlertController in Swift


Aasif Khan
By Aasif Khan | Last Updated on February 10th, 2024 7:19 am | 5-min read

In this app development tutorial, you’ll learn how to use the UIAlertController class to display alert dialogs in your iOS app. We’ll dive into setting up the alerts, responding to user actions, and getting input from the user with text fields.

The UIAlertController is a basic but important part of the iOS SDK, and it’s the default way to ask users to confirm an action. On top of that, UIAlertController also supports the action sheet, which is a convenient dialog style that allows your app’s users to quickly take action.

This tutorial is specially written for beginner iOS developers. Working with the UIAlertController is a fundamental topic for practical iOS developers.

Describe your app idea
and AI will build your App

Displaying Alerts with UIAlertController

“Are you sure?”

You’ve probably seen dozens of alert dialogs in iOS, Android, on the web, and on your Mac. Alert dialogs are as old as computers themselves! Even before computers had GUIs, you’d type “Y” or “N” at the command-line.

This is what an alert dialog looks like on iOS:

Alerts are crucial when building your app, to ask the user for confirmation of a sensitive action. Deleting data, signing out, giving permission, confirming a change — they’re tasks that your app’s user needs to explicitly confirm before continuing.

As you can see in the example alert above, alerts help with grouping similar actions together and presenting them as one. Do you want to make a backup before erasing? Do you want to pay with PayPal or checkout with your creditcard? Do you want to take this incoming call or send an “I’ll call you later” message?

Most alerts can’t be dismissed without taking an action, and that’s why they’re so effective. When an alert is presented, it fills the entire iPhone screen. You can’t move away without making a choice. Such an alert is known as a modal dialog. On iOS, they’re simply called alerts.

As a design rule, you should always have a Cancel option that dismisses the alert and reverts the app to its previous state. This helps a user who’s confused, and wants to go back without making a decision at all.

So… enough UI/UX talk. Let’s check out how you can create an alert with UIAlertController!

Here’s an example:

let alert = UIAlertController(title: “Did you bring your towel?”, message: “It’s recommended you bring your towel before continuing.”, preferredStyle: .alert)

alert.addAction(UIAlertAction(title: “Yes”, style: .default, handler: nil))
alert.addAction(UIAlertAction(title: “No”, style: .cancel, handler: nil))

self.present(alert, animated: true)
What’s happening here?

  • First, you create a constant called alert and assign a UIAlertController object to it. The initializer of UIAlertController takes three arguments: a title, a description and an alert controller style.
  • Then, you’re adding two actions to the alert: Yes and No. They’re the buttons that show in the dialog. More on actions later.
  • Finally, you’re presenting the alert on screen by calling the function present(_:animated:) on the current view controller; on self. This will display the alert to the user.

Here’s how the above code looks visually:

Using the UIAlertController(title:message:preferredStyle:) initializer is pretty straightforward. You provide a title and message as strings, and then choose an alert type from the UIAlertControllerStyle enumeration. In the above image you see the title and message. Optionally, you can leave either empty and create an alert with just a title or message.

You always have to “present” an alert, to show it to the user. Presenting a UIAlertController can only be done on a currently visible view controller that’s part of the view controller stack. Unless you’re doing something crazy, it’s most likely that you’re presenting the dialog from an active view controller already.

UIAlertController Styles: Alert or Action Sheet?

When creating your alert controller, with the UIAlertController( preferredStyle:) initializer, you can choose between two options:

  • A simple alert, with the .alert constant
  • An action sheet, with the .actionSheet constant

Here’s what that exact same alert looks like, with both options:

Action sheets are pretty cool. They have 3 benefits compared to alerts:

  1. Action sheets slide up from the bottom of the iPhone screen, so you can reach its buttons with your thumb. Easy!
  2. You can fit more text in an action sheet, compared to the alert style, for the title, message and buttons.
  3. Action sheet buttons fit more text, so you usually need less text for the title and message, compared to an alert.

When should you use an alert, and when an action sheet?

  • It’s best to use an action sheet for choosing between multiple similar options, like “Choose from Photo Library” and “Take Picture with Camera”. These options are mutually exclusive, and they belong to the same group: “Choose a picture from …” It’s a choice between “this or that”.
  • When you need explicit confirmation on a positive and negative action, like “Yes” and “No”, or “OK” and “Cancel”, it’s best to use an alert style dialog. It’s a choice between “this, or not this”.

Often, action sheets don’t have a title or message at all. Instead, you let the buttons speak for themselves. When you present a user with an action sheet, always give them the option to get out of the action sheet with a Cancel button.

Fun Fact: Prior to iOS 8, you would use the UIAlertView class to display alerts, and the UIActionSheet to display action sheets. You’d use the typical iOS target-action mechanism to respond to user interaction. Since then, those classes have been merged, and actions now take closures to respond to a user’s tap.

Responding to UIAlertController with Actions

The UIAlertController class provides you with a mechanism to respond to user interaction. When a user taps an action you’ve attached to your alert, it calls a closure you’ve associated with that action.

Like this:

alert.addAction(UIAlertAction(title: “Yes”, style: .default, handler: { action in
print(“Yay! You brought your towel!”)
}))
When you deconstruct the above example code, you’ll find this:

  • You can add actions to an alert with the addAction(_:) function. It takes one argument, an instance of UIAlertAction.
  • You initialize an UIAlertAction with a title, a style and a handler. The handler is a closure, and the style is a constant from the enum UIAlertActionStyle.

Within the closure you can define what happens when the action is executed, i.e. what happens when the user taps the alert button. In the above code, this is the closure that’s executed:

{ action in
print(“Yay! You brought your towel!”)
}
The closure has one parameter action of type UIAlertAction. It’s a reference to the action that’s invoked and it allows you to distinguish between actions, for example when you use one closure for multiple actions.

Actions, and their buttons, can have three styles:

  • Default, with the constant .default
  • Cancel, with the constant .cancel
  • Destructive, with the constant .destructive

By default, the .cancel action is highlighted in the alert. You can see that in the example images above. The cancel option is effectively biased, which means the user has to make a conscious effort to confirm an alert. This means they’re less likely to make a mistake!

The .destructive style is usually red, indicating to your app’s users that this is a dangerous action or one that cannot be undone.

Even if you change the order of adding the actions to the alert, the Cancel button is always shown first. The UIAlertController can also have a preferred action. When specified, the alert then highlights that action.

The cancel button is the preferred action by default. You can also assign an action yourself, but you’ll first have to add it with the addAction(_:) function before assigning it to the preferredAction property of UIAlertController.

Working with User Input in Alert Text Fields

One last thing…

You can also add a text field to an alert. Like this:

let alert = UIAlertController(title: “What’s your name?”, message: nil, preferredStyle: .alert)
alert.addAction(UIAlertAction(title: “Cancel”, style: .cancel, handler: nil))

alert.addTextField(configurationHandler: { textField in
textField.placeholder = “Input your name here…”
})

alert.addAction(UIAlertAction(title: “OK”, style: .default, handler: { action in

if let name = alert.textFields?.first?.text {
print(“Your name: \(name)”)
}
}))

self.present(alert, animated: true)
In the above code sample, this happens:

  • First, you create an UIAlertController instance with type .alert.
  • Then, you’re adding a simple Cancel action.
  • Then, you’re adding a text field with the addTextField(configurationHandler:) function. You can use the closure to configure the text field, like setting the placeholder property. When you want to use the input from the text field, you have to use one of the actions.
  • Finally, you’re adding an action that says OK. When this action is invoked, the input from the text field is printed out to the debugger with print. You can access the text field by using the textFields array on the alert.

And here’s what it looks like in your app:

Pretty neat, right? This effectively turns the alert into a prompt you can use to quickly ask for user input.

Further Reading

And that’s all there is to using alerts! You now know how to create one, how to configure it, how to respond to user actions, and why it’s sometimes better to use an action sheet than an alert dialog. Awesome!


Aasif Khan

Head of SEO at Appy Pie

App Builder

Most Popular Posts