0

I am attempting to present a tableViewController embedded in a NavigationController on top of a ViewController embedded in a NavigationController.

I keep getting the error: that the view controller cannot be presented because it is not in the window hierarchy.

In short, I'm trying to allow a user to click on the number of likes on a post and then be directed to an embedded TableViewController in NavigationController and it's not working.

For some reason it works when being presented from a tab bar controller when I try clicking on the like number but not when I do it from a navigation controller. The code for the action of clicking the like number is as follows and is located in a collection view cell swift file:

 @IBAction func LikeNumber_tapped(_ sender: Any) {
        let vc = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "LikedByVC2") as? UINavigationController
        let tableVC = vc?.viewControllers.first as! LikedByTableViewController
        tableVC.postKey = self.postKey
        self.window?.rootViewController?.present(vc!, animated: true, completion: nil)

    }

Is it possible to do what I am attempting? I tried to make the question as simple as possible but let me know if I need to elaborate more. Thanks in advance.

dombad
  • 25
  • 5
  • Why are you doing that? Why not `self.navigationController?.pushViewController(vc,animated:false)`? or why not just use a segue? – Paulw11 Sep 23 '17 at 06:09
  • @Paulw11 I can't use push because "self" is a collectionviewcell so I am limited to the options that I have to show another view controller. And I'm unsure how a segue would help me to show the view controller. – dombad Sep 23 '17 at 18:07
  • Ok, if `self` is a cell then you should use a delegation and the button tap event out to the correct view controller so that it can be processed. Basic approach [here](https://stackoverflow.com/questions/28659845/swift-how-to-get-the-indexpath-row-when-a-button-in-a-cell-is-tapped/38941510#38941510). And showing view controllers is what segues do. – Paulw11 Sep 23 '17 at 22:14

1 Answers1

0

A solution could be to replace the last line with this:

UIApplication.shared.keyWindow?.rootViewController?.present(vc!, animated: true, completion: nil)

For more information and various solutions you could also check this thread

TheoK
  • 3,601
  • 5
  • 27
  • 37
  • I still get the same error. It says the following: "Warning: Attempt to present on whose view is not in the window hierarchy!" It must have something to do with the fact that it goes from a tabbarcontroller to a navigation controller and then what I'm trying to present should be going over that navigation controller but is trying to present itself on the tabbarcontroller. This is the problem that I'm running into. – dombad Sep 23 '17 at 18:05