— Swift, iOS, AppDelegate, UIAlertController — 1 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.
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.
Before diving into the code, ensure you have:
First, import the UIKit
framework in your AppDelegate.swift
file.
1import UIKit
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 return4 }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}
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}
DispatchQueue.main.async
if you're unsure about the current thread.