Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

iOS

Presenting pop overs

So i currently have a pop over which is presented to the user when they press a button. The problem i'm having is that i can't seem to dismiss this view controller and then present the view controller which should appear when the button has been pressed.

Is there anyway to dismiss a view controller but still present another here is my code below?

    @IBAction func unlockButtonDidTouch(sender: AnyObject) {

        dismissViewControllerAnimated(true) { () -> Void in

            let storyboard = UIStoryboard(name: "Main", bundle: nil)
            let vc = storyboard.instantiateViewControllerWithIdentifier("unlockVC") as! UnlockViewController
            self.presentViewController(vc, animated: true, completion: nil)

        }


    } 

Here is the error which i an getting

2015-12-25 19:34:40.008 Corral[771:165154] Warning: Attempt to present <Corral.UnlockViewController: 0x1672df70> on <Corral.UnlockViewController: 0x16734850> whose view is not in the window hierarchy!

The issue is that the view you are dismissing is not complete yet, then you are trying to present another view.

You need to add a slight delay to let the view dismiss, once that is done, then present the new view.

2 Answers

An example would be

  self.dismissViewControllerAnimated(true, completion: { () -> Void in // Dismiss

                dispatch_async(dispatch_get_main_queue(), { () -> Void in // Delay

                    self.presentViewController(presentYourView, animated: true, completion: nil) // Present
                })
            })   
        }

This doesn't really work mate it still displays the same error as before

Tunde,

What error message are you getting?

Where are you calling this method from? I had an issue where I was attempting to present a modal view controller within the viewDidLoad method. The solution for me was to move this call to the viewDidAppear: method.

My presumption is that the view controller's view is not in the window's view hierarchy at the point that it has been loaded (when the viewDidLoad message is sent), but it is in the window hierarchy after it has been presented (when the viewDidAppear: message is sent).

Another solution to this problem is to add view to the view controller and hide it. Then when the user presses the button.. you can set hidden to false.