Jon Gardocki
Jon Gardocki

Reputation: 37

UIAlertController is complete and presented but does not appear during viewDidLoad

I have this alert controller setup to appear as soon as the view controller is loaded. However, it does not appear. I believe I have all the facets covered - title, message, alert style, action button and present... but still does not appear. Unsure what I'm missing.

  let array = quoteBank()

    print(array.sarcasticQuotes[0].quote)


    let title = "Message"
    let message = array.sarcasticQuotes[0].quote

    let alert = UIAlertController(title: title, message: message, preferredStyle: .alert)

    alert.addAction(.init(title: "OK", style: .default, handler: nil))
   present(alert, animated: true, completion: nil)

Upvotes: 0

Views: 139

Answers (2)

Mo Abdul-Hameed
Mo Abdul-Hameed

Reputation: 6110

You need to perform that on the main thread:

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

The reason behind that is that the view controller's hierarchy will be set after viewDidLoad is finished. So by doing this, you're scheduling the presentation of the alert on the main thread to the time the main thread is finished from executing viewDidLoad.

Upvotes: 0

rmaddy
rmaddy

Reputation: 318954

Attempting to show an alert in viewDidLoad is too soon. The view controller isn't displayed yet. Use viewDidAppear.

override func viewDidAppear(_ animated: Bool) {
    super.viewDidAppear(animated)

    // Use this if statement to only show the alert once
    if self.isBeingPresented || self.isMovingToParentViewController {
        // show your alert here
    }
}

Upvotes: 3

Related Questions