sulabh qg
sulabh qg

Reputation: 1235

Can't present alertViewController on rootViewController in AppDelegate

I want to show alertViewController on my rootViewController in AppDelegate when app is launched. Here snippet of code:

 func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
        let alert: UIAlertController = UIAlertController(title: "This is title", message: "This is message.", preferredStyle: UIAlertControllerStyle.alert)
        alert.addAction(UIAlertAction(title: "Ok", style: .default))
        self.window?.rootViewController?.present(alert, animated: true, completion: nil)
        return true
 }

alert is not appearing on rootViewController. Please help me.

Upvotes: 0

Views: 221

Answers (1)

Shehata Gamal
Shehata Gamal

Reputation: 100503

The reason is that the view isn't yet loaded, if you look at console you may find log like this:

Warning: Attempt to present on 'swiftHere.ViewController: 0x7ff289007740' whose view is not in the window hierarchy!

You may dispatch it until rootViewController loads:

DispatchQueue.main.asyncAfter(deadline: .now() + 2) {

       let alert: UIAlertController = UIAlertController(title: "This is title", message: "This is message.", preferredStyle: UIAlertControllerStyle.alert)
       alert.addAction(UIAlertAction(title: "Ok", style: .default))
      self.window?.rootViewController?.present(alert, animated: true, completion: nil)

    }

Upvotes: 2

Related Questions