How to show UIAlertController from Appdelegate

前端 未结 6 1725
后悔当初
后悔当初 2020-11-30 01:32

I\'m working with PushNotification on iOS app. I would like to show a UIalertcontroller when the app receive a notification.

I try this code below in the AppDelegate

6条回答
  •  情歌与酒
    2020-11-30 02:15

    Shortest & Simplest :

    Create a extension :

    extension UIApplication {
    class func topViewController(controller: UIViewController? = UIApplication.shared.keyWindow?.rootViewController) -> UIViewController? {
        if let navigationController = controller as? UINavigationController {
            return topViewController(controller: navigationController.visibleViewController)
        }
        if let tabController = controller as? UITabBarController {
            if let selected = tabController.selectedViewController {
                return topViewController(controller: selected)
            }
        }
        if let presented = controller?.presentedViewController {
            return topViewController(controller: presented)
        }
        return controller
    } }
    

    and then use it anywhere like

    UIApplication.topViewController()?.present(UIViewController, animated: true, completion: nil)
    

    With this you can present Alert or anything Anywhere Example :

    let alert = UIAlertController(title: "Your title", message: "Your message", preferredStyle: .alert)
    let cancelButton = UIAlertAction(title: "Ok", style: .cancel, handler: nil)
    alert.addAction(cancelButton)
    UIApplication.topViewController()?.present(alert, animated: true, completion: nil)
    

    ALTERNATE METHOD :

    No need to create any Extension or any method or anything simply write the above 3 lines for creating an Alert and for presenting use :

    self.window?.rootViewController?.present(alert, animated: true, completion: nil)
    

    That's it.! =)

提交回复
热议问题