Vladimir Nul Vladimir Nul - 6 months ago 8
Swift Question

UINavigationController "acting crazy" after I added a new initial UIViewController

I had a UINavigationController set as initial view controller. The root view controller for that navigation controller shows a menu where users can see product categories (In case that's interesting for anyone :)). The root view controller loads JSON data from an URL, so it takes a little while until the view shows up (which is fine). That data will be use in all the app, so it's an important step.

Well, since the data load takes a while, I added a new UIViewController where I show an image with an UIActivityIndicator. Of course, the data load takes place in this UIViewController now instead of the root view controller.

So, the idea is that after the data is loaded, the root view controller takes the place. To accomplish this I put an "invisible" UIButton on the new view controller and added a UIStoryboardSegue to the navigation controller, so I trigger that segue programmatically after the data is loaded.

After the data gets loaded, the navigation controller actually appears and shows (of course) the root view controller. The problem is when I click any button on the root view controller, the segue performs correctly, but from the "second" view controller (UITableViewController) if I press any cell, it takes me back to the new view controller (the one that shows an image and loads the data). Well not actually any cell, because sometimes it takes me actually forwards to the "third" view controller (also UITableViewController), but the same problem occurs in this view controller. If I click the back button on the navigation bar in any view controller, it takes me back to the new view controller and not really back in the navigation stack.

Here is ViewDidLoad:

override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)

load.loadAllProducts()
load.loadCategories()

self.performSegueWithIdentifier("mainStoryboardSegue", sender: self)
}


And PrepareForSegue:

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
let destination = segue.destinationViewController as? UINavigationController
let homeViewController = destination!.viewControllers.first as? HomeViewController
homeViewController!.categories = load.categories
homeViewController!.products = load.products
}


I really appreciate any help, thanks a lot!

Answer

The solution that worked for me was to change the current active view controller by setting this:

let newController = storyboard.instantiateViewControllerWithIdentifier(storyboardId) as? UINavigationController
UIApplication.sharedApplication().keyWindow!.rootViewController = newController
Comments