DEV Community

Cover image for The easiest way to handle UIAlertController in Swift
Shu
Shu

Posted on

The easiest way to handle UIAlertController in Swift

UIKit provides UIAlertController, but it is sometimes annoying to use. You have to get the top UIViewController. I will introduce an easier way to handle UIAlertController.

// AlertController.swift

UIKit 

class AlertController: UIAlertController {
    private lazy var alertWindow: UIWindow = {
        let window = UIWindow(frame: UIScreen.main.bounds)
        window.rootViewController = ClearViewController()
        window.backgroundColor = UIColor.clear
        window.windowLevel = UIWindow.Level.alert
        return window
    }()

    /// Shows a custom alert controller.
    func show(animated flag: Bool = true, completion: (() -> Void)? = nil) {
        guard let rootVC = alertWindow.rootViewController else { return }
        alertWindow.makeKeyAndVisible()
        rootVC.present(self, animated: flag, completion: completion)
    }
}

private class ClearViewController: UIViewController {
    override var preferredStatusBarStyle: UIStatusBarStyle {
        return UIApplication.shared.statusBarStyle
    }

    override var prefersStatusBarHidden: Bool {
        return UIApplication.shared.isStatusBarHidden
    }
}
Enter fullscreen mode Exit fullscreen mode

You can use AlertController like following. This alert will allow you to show an alert view from anywhere easily. I mean, You don't have to call present(viewControllerToPresent: UIViewController>, animated: Bool, completion: (() -> Void)?) from UIViewController anymore.

func displayAlert() {
    let alert = AlertController(title: "Error", message: "Something happened", preferredStyle: .alert)
    let action = UIAlertAction(title: "OK", style: .default)
    alert.addAction(action)
    alert.show()
}
Enter fullscreen mode Exit fullscreen mode

You might want to extend Error like below. You can show an error alert like error.displayAlert(). It's easy, isn't it?

extension Error {
    func displayAlert(completion: (() -> Void)? = nil) {
        let alert = AlertController(title: "Error", message: localizedDescription, preferredStyle: .alert)
        let action = UIAlertAction(title: "OK", style: .default)
        alert.addAction(action)
        alert.show(completion: completion)
    }
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)