Simple App Delegate method to show an UIAlertController (in Swift)

为君一笑 提交于 2019-11-28 18:35:32
ZeMoon

Try using

self.window?.rootViewController?.presentViewController(importAlert, animated: true, completion: nil)

All you need is a viewController object to present the AlertController from.

In Swift 4:

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

Use this code to launch alertCV from appdelegate

    dispatch_async(dispatch_get_main_queue(), {
          let importantAlert: UIAlertController = UIAlertController(title: "Action Sheet", message: "Hello I was presented from appdelegate ;)", preferredStyle: .ActionSheet)
        self.window?.rootViewController?.presentViewController(importantAlert, animated: true, completion: nil)
    })

Hope this helps!

Marie Amida

The best way I've found is the following:

        let importantAlert: UIAlertController = UIAlertController(title: "Action Sheet", message: "Hello I was presented from appdelegate ;)", preferredStyle: .ActionSheet) //.Alert .ActionSheet
        var hostVC = UIApplication.sharedApplication().keyWindow?.rootViewController
        while let next = hostVC?.presentedViewController {
            hostVC = next
        }
        hostVC?.presentViewController(importantAlert, animated: true, completion: nil)


        let delay = 1.5 * Double(NSEC_PER_SEC)
        let time = dispatch_time(DISPATCH_TIME_NOW, Int64(delay))
        dispatch_after(time, dispatch_get_main_queue()) {

            importantAlert.dismissViewControllerAnimated(true, completion: nil)

            return
        }

I've added a timer so the UIAlertController is dismissed since it doesn't have any buttons in it.

Thanks to: https://stackoverflow.com/a/33128884/6144027 Brilliant answer on how to present a UIAlertController from AppDelegate.

From inside the app delegate.

window.rootViweController.presentViewController...

The accepted answer in Swift 3 in case it helps anyone:

self.window?.rootViewController?.present(importAlert, animated: true, completion: nil)
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!