1

I am trying to make an in-app popup alert using swift and I have run into an error that I know nothing about.

Here is the code I use to present my alert:

let welcomeAlert = UIAlertController(title: "Welcome!", message: “message here”, preferredStyle: UIAlertControllerStyle.Alert)
welcomeAlert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.Default, handler: nil))
self.presentViewController(welcomeAlert, animated: true, completion: nil)

println("welcome alert displayed!")

The error I'm getting back says this:

Warning: Attempt to present <UIAlertController: 0x7b89a950> on <MyApp.RootClientViewController: 0x7aea8fb0> whose view is not in the window hierarchy!

This is immediately followed by a printed statements stating welcome alert displayed!.

So my code is certainly running, but for some reason, it won't display the alert...

What am I doing wrong?

MoralCode
  • 1,954
  • 1
  • 20
  • 42

1 Answers1

4

The error message tells you the answer: "view is not in the window hierarchy!" means self.view is not on screen when the call is made (technically it means UIApplication.sharedApplication().keyWindow is not an ancestor of self.view).

Usually this happens when presenting a view controller in viewDidLoad() or viewWillAppear(animated: Bool). Wait for viewDidAppear(animated: Bool), present from UIApplication.sharedApplication().delegate.window.rootViewController or present from UIApplication.sharedApplication().keyWindow.rootViewController.

Jeffery Thomas
  • 42,202
  • 8
  • 92
  • 117
  • 1
    The problem is trying to present a view controller from a view controller which is not on screen. You can check this with `self.view. isDescendantOfView(UIApplication.sharedApplication().keyWindow)`. Whenever this is `true`, you can present a view controller. – Jeffery Thomas Nov 29 '14 at 15:44
  • Oh okay! So I'd just put that code in an if statement to check if I can present my alert? – MoralCode Nov 29 '14 at 16:06
  • Let me back up here, normally the test is not needed. You need to know the view controller's lifecycle (specifically, what parts run on screen and what parts run off screen). From `viewDidAppear(animated: Bool)` up until `viewDidDisappear(animated: Bool)` are all on screen. Anything else is off screen. – Jeffery Thomas Nov 30 '14 at 03:11