Was trying to show an alert dialog in a project’s AppDelegate.swift and ViewController.swift and decided to move it to a function in a separate utility class. Main issue was how to make it work as the class was a plain Swift class – self.present() could be used inside ViewController, self.window?.rootViewController?.present() could be used inside AppDelegate, but a plain Swift class?
Here’s my humble and simple solution, adapted from this StackOverflow answer. Just a note that AppDelegate may need to declare a var window = UIWindow?.
// Util.swift
import UIKit
/**
* Common utility functions
*/
class Util {
/**
* Show alert dialog
*
* @param title Dialog title
* @param message Dialog message
* @return void
*/
static func showAlert(_ title: String, _ message: String) {
let alert = UIAlertController(
title: title,
message: message,
preferredStyle: UIAlertControllerStyle.alert
)
alert.addAction(UIAlertAction(
title: "OK",
style: UIAlertActionStyle.default,
handler: nil
))
UIApplication.shared.keyWindow?.rootViewController?.present(
alert,
animated: true,
completion: nil
)
}
}

