0

So the first thing my app does is get a list of movies from an API. I'm trying to handle if there's a network issue. Currently, in my viewDidLoad method, I call "updateApiInfo", which contains the following code:

if self.movies == nil {
            print("stuff went wrong")
            let alert = UIAlertController(title: "Network Error", message: "There was a nework error.\nYou must be connected to the internet to use Flicks.", preferredStyle: UIAlertControllerStyle.Alert)
            alert.addAction(UIAlertAction(title: "Exit", style: UIAlertActionStyle.Default, handler: {(UIAlertAction) in
                UIControl().sendAction(Selector("suspend"), to: UIApplication.sharedApplication(), forEvent: nil)
            }))
            self.presentViewController(alert, animated: true, completion: nil)
}

When viewDidLoad calls updateApiInfo, I get this message:

Warning: Attempt to present <UIAlertController: 0x7fad10e3ad80> on <Flicks.MoviesViewController: 0x7fad10e35cc0> whose view is not in the window hierarchy!

When I call updateApiInfo just from the user refreshing, the error pops up as expected.

I'm assuming that viewDidLoad only gets called before the view gets displayed to the user, which I guess is causing this error. Is there a method I can stick this code in for after the view is displayed to the user, so the problem can presumably get fixed?

CaptainForge
  • 1,365
  • 7
  • 21
  • 46
  • No, `viewDidLoad` is called when the view is instantiated, but before it is presented. You'd generally use `viewDidAppear` for stuff after the view is actually presented. – Rob Jan 21 '16 at 01:38
  • That's right. `viewDidLoad()` only guarantees that the view controller's main view is instantiated (and any subviews defined in Interface Builder, too). – Nicolas Miari Jan 21 '16 at 01:51
  • @CaptainForge - did my answer below answer your question? – siburb Jan 28 '16 at 07:14

1 Answers1

2

You need to use viewDidAppear: to make sure the view is already in the window hierarchy.

There's a pretty good explanation of the order in which the methods are called here: What is the process of a UIViewController birth (which method follows which)?

Community
  • 1
  • 1
siburb
  • 4,880
  • 1
  • 25
  • 34