2

I'm trying to add a UIAlertView or Controller when the app first loads. Currently, I have this code in my viewDidLoad method.

let welcomeAlert = UIAlertController(title: "hola", message: "this is a test.", preferredStyle: UIAlertControllerStyle.Alert)
welcomeAlert.addAction(UIAlertAction(title: "ok.", style: UIAlertActionStyle.Default, handler: nil))

self.presentViewController(welcomeAlert, animated: true, completion: nil)

Why won't the alert view display? I used the same code but inside of an IBAction for a button, and it works as expected.

Jojodmo
  • 23,357
  • 13
  • 65
  • 107
Amit Kalra
  • 4,085
  • 6
  • 28
  • 44
  • That's a dup. You can't display an alert from the root VC. See http://stackoverflow.com/questions/10147625/unable-to-get-presentviewcontroller-to-work for alternatives. – John Difool Jun 14 '15 at 22:58

1 Answers1

6

You should be displaying the alert in your viewDidAppear: function. To present a subview or another view controller, the parent view controller has to be in the view hierarchy.

The viewDidAppear function "notifies the view controller that its view was added to a view hierarchy."

* From the documentation

So, your code could look something like this:

class MyViewController: UIViewController {

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

        let welcomeAlert = UIAlertController(title: "hola", message: "this is a test.", preferredStyle: UIAlertControllerStyle.Alert)
        welcomeAlert.addAction(UIAlertAction(title: "ok.", style: UIAlertActionStyle.Default, handler: nil))
        self.presentViewController(welcomeAlert, animated: true, completion: nil)
    }

}
Community
  • 1
  • 1
Jojodmo
  • 23,357
  • 13
  • 65
  • 107
  • I don't have that in my code. I don't see a viewDidAppear. And if I insert what you have, it tells me to remove the didReceiveMemoryWarning – Amit Kalra Jun 15 '15 at 00:05
  • You have to add the function, and what is the entire error message about `didReceiveMemoryWarning`? Maybe you forgot a curly brace (`}`) when putting the code in. – Jojodmo Jun 15 '15 at 00:14
  • Ah, I put it under the memory thing and it worked fine. – Amit Kalra Jun 15 '15 at 00:21