Async/await UIAlertController

Published by malhal on

I needed to show an alert in an async context and this is how I achieved it:

func loseEditsAlert() async throws {
    try await withCheckedThrowingContinuation { continuation in
        let alert = UIAlertController(title: "Opening link", message: "OK to lose your edits?", preferredStyle: .alert)

        let action = UIAlertAction(title: NSLocalizedString("OK", comment: "Default action"), style: .default) { _ in
        let cancel = UIAlertAction(title: "Cancel", style: .cancel) { _ in
            continuation.resume(throwing: CancellationError())

        present(alert, animated: true)

The idea to throw a cancellation exception was inspired by DDDevicePickerViewController which is the only built-in async UIViewController I’m aware of.