0

I've got an application that should open an Alert View Controller in the viewDidLoad()-function. It's a simple reminder app. Here's the piece of code:

let alert = UIAlertController(title: "Reminder", message: "Your reminder text", preferredStyle: UIAlertControllerStyle.alert)
    alert.addAction(UIAlertAction(title: "Sure!", style: UIAlertActionStyle.default) {
        (finished) in
        self.didReceiveRemoteNotificationAction()
    })
    self.present(alert, animated: true, completion: nil)

But the problem is: it doesn't show up! Can anyone explain to me why?

I do know that my Storyboard is very... interleaved with views. But that shouldn't be a problem, right?

Mo Abdul-Hameed
  • 6,030
  • 2
  • 23
  • 36
Carl Henretti
  • 457
  • 2
  • 7
  • 17

2 Answers2

0

When viewDidLoad is triggered, the view controller's view is not in the window hierarchy yet, and this is why your alert is not being presented.

You should put your alert presentation code inside viewDidAppear instead of viewDidLoad.

This answer talks about the same problem and explains an alternative option that uses GCD.

This answer has a good discussion about viewDidLoad and viewDidAppear.

Good luck!

Community
  • 1
  • 1
Mo Abdul-Hameed
  • 6,030
  • 2
  • 23
  • 36
0

That's because you're calling it from the ViewDidLoad, your views are not set yet! You have two options:

  • Call it from ViewDidAppear (suggested).
  • Call it using GCD thread :

    DispatchQueue.main.async { self.present(alert, animated: true, completion: nil) }

fethica
  • 759
  • 6
  • 10