Nurdin
Nurdin

Reputation: 23893

Swift - warning: attempt to present on whose view is not in the window hierarchy

I got this problem when I click back button inside my SecondViewController.

2014-12-24 12:08:58.838 UPASS[5158:71438] Warning: Attempt to present <APPNAME.ThirdViewController: 0x7ae6bcc0> on <APPNAME.SecondViewController: 0x7af72060> whose view is not in the window hierarchy!

code

import UIKit

class SecondViewController: UIViewController {

    @IBAction func btnSubmit(sender: AnyObject) {
        let storyBoard : UIStoryboard = UIStoryboard(name: "Main", bundle:nil)

        let thirdViewController = storyBoard.instantiateViewControllerWithIdentifier("successView") as ThirdViewController
        self.presentViewController(thirdViewController, animated:true, completion:nil)
    }

    @IBAction func btnBack(sender: AnyObject) {
        let storyBoard : UIStoryboard = UIStoryboard(name: "Main", bundle:nil)

        let firstViewController = storyBoard.instantiateViewControllerWithIdentifier("methodView") as FirstViewController
        self.presentViewController(firstViewController, animated:true, completion:nil)

    }

    override func viewDidLoad() {
        super.viewDidLoad()

        self.view.backgroundColor = UIColor(patternImage: UIImage(named: "bgCreateUser.jpg")!)
        // Do any additional setup after loading the view.
    }


}

Upvotes: 1

Views: 6536

Answers (4)

dbrownjave
dbrownjave

Reputation: 487

Developers can receive this warning when performing a segue from a view controller that is embedded in container.

Helpful Solution: Use segue from the parent of container, not from container's view controller (eg. back button)

Upvotes: 0

Nurdin
Nurdin

Reputation: 23893

What I did is delete all my buttons inside SecondViewController and add them back. My huge mistake is I copy it from somewhere else.

Upvotes: 3

Woodster
Woodster

Reputation: 3461

The error message complains about "ThirdViewController", which is not referenced by the "btnBack" method, but is referenced in the btnSubmit method.

That suggests that perhaps both btnBack and btnSubmit are being called when you tap the "back button". This happens if you connected one of them as an action and then connected the other method to the same button.

Verify that you only have one of them connected by selecting the button in Interface Builder (the storyboard editor), then use the Connections Inspector (Command+Option+6) and ensure that only one of them is connected to the button.

Upvotes: 1

Woodster
Woodster

Reputation: 3461

Is btnBack supposed to go back to an earlier view controller? If so, instead of presenting a fresh instance, return to the previous one using:

dismissViewControllerAnimated(true, completion:nil)

Upvotes: 3

Related Questions