Create a UIAlertController with the .alert style, add at least one UIAlertAction, and call present(_:animated:) from a view controller that is on screen, on the main thread. Wrap it in a small UIViewController extension so every screen shows alerts the same way, and use an async version when you need the user's answer before you continue.
SWIFT TIPS · UIKIT
First posted on April 4, 2018 for Swift 4, as "Simple Notification Alert for App Use Swift 4". Rewritten on November 17, 2026. The Swift code below was type-checked on a Mac with Xcode 26.2 against the iOS 26.2 SDK, in Swift 5 and Swift 6 language modes, with iOS 15 as the deployment target. It wasn't run on a device.
The 2018 post was eight words and one button action: show an alert that says the form is empty, with a Close button. It's the first thing most UIKit developers learn, and the snippet still works. What it doesn't show is where alerts go wrong in a real app: the alert that never appears, the one shown from a background thread, and the copy-pasted block in every screen that slowly drifts apart.
Here is the version I'd paste into a project today.
The alert helper
import UIKit
extension UIViewController {
/// Shows a one-button alert from this view controller.
func showAlert(title: String, message: String, buttonTitle: String = "OK",
onDismiss: (() -> Void)? = nil) {
let alert = UIAlertController(title: title, message: message, preferredStyle: .alert)
alert.addAction(UIAlertAction(title: buttonTitle, style: .default) { _ in onDismiss?() })
present(alert, animated: true)
}
/// Asks a yes/no question and returns the answer with async/await.
func confirm(title: String, message: String, confirmTitle: String,
isDestructive: Bool = false) async -> Bool {
await withCheckedContinuation { continuation in
let alert = UIAlertController(title: title, message: message, preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "Cancel", style: .cancel) { _ in
continuation.resume(returning: false)
})
let confirm = UIAlertAction(title: confirmTitle, style: isDestructive ? .destructive : .default) { _ in
continuation.resume(returning: true)
}
alert.addAction(confirm)
if !isDestructive { alert.preferredAction = confirm }
present(alert, animated: true)
}
}
/// The view controller that is currently on top of this one.
var topMostPresented: UIViewController {
var top: UIViewController = self
while let next = top.presentedViewController, !next.isBeingDismissed { top = next }
return top
}
}
final class FormViewController: UIViewController {
@IBAction func saveTapped(_ sender: UIButton) {
showAlert(title: "Data is empty", message: "Please fill in every field before saving.") {
print("Alert closed")
}
}
@IBAction func deleteTapped(_ sender: UIButton) {
Task {
let ok = await confirm(title: "Delete this draft?", message: "You can't undo this.",
confirmTitle: "Delete", isDestructive: true)
if ok { print("Deleting") }
}
}
func loadFailed(_ error: Error) {
topMostPresented.showAlert(title: "Couldn't load", message: error.localizedDescription)
}
func refresh(url: URL) {
Task {
do {
_ = try await URLSession.shared.data(from: url)
} catch {
loadFailed(error) // back on the main actor here
}
}
}
}
The extension gives every view controller three things:
showAlert(title:message:)for a plain message with one button. The optional closure runs after the user taps it, which is where you'd clear the form or go back.confirm(...), which waits for a yes or no withasync/await. The delete example reads top to bottom instead of nesting the follow-up inside an action handler.topMostPresented, which walks up the chain of presented screens. Use it when the alert can come from anywhere, like a failed network call while a sheet is open.
Two details in confirm are deliberate. The cancel action uses the .cancel style, so UIKit places it where people expect a cancel button. And for a non-destructive confirm, preferredAction bolds the main button. Apple's documentation says the preferred action is highlighted and that pressing Return on a connected keyboard triggers it. I leave it off for destructive actions so Return doesn't delete anything.
Where alerts go wrong
Showing it from a background thread
The classic bug is presenting an alert from inside a network callback. URLSession calls its completion handler on a background queue, and UIKit isn't safe to use there. I checked how the compiler treats that today with a small file that does exactly this. In Swift 5 mode it compiled without a word. In Swift 6 mode it compiled too, but with two warnings:
o004_offmain.swift:7:29: warning: call to main actor-isolated initializer 'init(title:message:preferredStyle:)' in a synchronous nonisolated context
o004_offmain.swift:8:22: warning: call to main actor-isolated instance method 'present(_:animated:completion:)' in a synchronous nonisolated context
So the compiler tells you, but it doesn't stop you. Don't ignore those warnings. The fix in the helper above is to do the work in a Task started from the view controller: the await suspends, and when it resumes the code is back on the main actor, so calling loadFailed is safe.
Presenting while something else is on screen
A view controller can only present one thing at a time. If a sheet or another alert is already up, calling present on the screen underneath won't show your alert, and UIKit only reports it in the console. That's why the error path above goes through topMostPresented, which skips a screen that is in the middle of being dismissed. I didn't run this case on a device for this rewrite.
Showing it before the screen is visible
Calling present in viewDidLoad is too early, because the view isn't in a window yet. If an alert has to appear as soon as a screen opens, show it from viewDidAppear(_:), and keep a flag so it doesn't come back every time the user returns to that screen.
Writing the text
The 2018 alert said "Empty" with the message "Your data is empty, please compete data". Apart from the typo, the title doesn't tell the user what to do. A few habits make alerts easier to read:
- Put the problem in the title and the fix in the message: "Data is empty" and "Please fill in every field before saving."
- Name buttons after what they do. "Delete" is clearer than "OK" when the alert asks whether to delete.
- Use an alert for something the user has to deal with now. For "saved" or "copied", a short message inside the screen interrupts less.
A quick check for your project
- Search the project for
UIAlertController(. If the same few lines appear in many screens, move them into one helper like the one above. - Turn on Swift 6 language mode for one module, or set Strict Concurrency Checking to Complete, and look for
main actor-isolatedwarnings near alerts. Each one is a place where an alert may be shown off the main thread. - Open a sheet in your app, then trigger an error that shows an alert. If nothing appears, that path needs
topMostPresented.
What the 2018 version said
The original had this action, which still compiles:
@IBAction func yourButton(_ sender: Any) {
let alert = UIAlertController(title: "Empty", message: "Your data is empty, please compete data", preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "Close", style: .default, handler: { (action: UIAlertAction) in
print("OK Cancel")
}))
self.present(alert, animated: true, completion: nil)
}
It's fine for one screen. The helper above is the same idea, written once, with the two extra cases most apps run into.
Keep reading on JR Devhub
Comments