Skip to content
DeveloperMemos

Displaying Alerts in AppDelegate with Swift

Swift, iOS, AppDelegate, UIAlertController1 min read

Managing alerts in an iOS application can sometimes require showing them from the AppDelegate. This article demonstrates how to effectively display alerts from the AppDelegate in a Swift application.

Understanding the Challenge

The primary challenge in displaying alerts from the AppDelegate is ensuring that the view controller from which the alert is presented is part of the window hierarchy. This can be particularly tricky during app initialization or when handling remote notifications.

Prerequisites

Before diving into the code, ensure you have:

  • Xcode installed on your Mac.
  • Basic understanding of Swift and iOS app development.

Step-by-Step Guide

Step 1: Importing UIKit

First, import the UIKit framework in your AppDelegate.swift file.

1import UIKit

Step 2: Presenting the Alert

You need to present the alert from a view controller that is in the window hierarchy. One common approach is to use the root view controller of the window.

Here's an example function in AppDelegate that does this:

1func showAlert(title: String, message: String) {
2 guard let rootViewController = self.window?.rootViewController else {
3 return
4 }
5
6 let alertController = UIAlertController(title: title, message: message, preferredStyle: .alert)
7 let action = UIAlertAction(title: "OK", style: .default, handler: nil)
8 alertController.addAction(action)
9
10 rootViewController.present(alertController, animated: true, completion: nil)
11}

Step 3: Calling the Function

You can now call this function whenever you need to show an alert. For example, in response to a remote notification:

1func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any]) {
2 showAlert(title: "Notification Received", message: "You have a new message.")
3}

Tips and Considerations

  • Window's Root View Controller: Ensure that the window's root view controller is set before presenting the alert.
  • Thread Safety: Always present UI elements on the main thread. Use DispatchQueue.main.async if you're unsure about the current thread.
  • Multiple Alerts: Be cautious about presenting multiple alerts at once, as it can degrade the user experience.