Search code examples
iosiphoneswiftsegue

Prepare for Segue to UITabBarController Tab


I want to pass information from a ViewController to a UITabBarController so that I can access certain information from the view controller in the 3rd tab of the UITabBarController.

However, the issue is my program keeps crashing when I try to do so. Here is my code so far:

I call the segue like so:

self.firstName = user.first_name
self.lastName = user.last_name
self.performSegueWithIdentifier("OffersView", sender: self)

And I override the prepareForSegue function so that I can pass information in this function like so:

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
    if(segue.identifier == "OffersView"){
        let barViewControllers = segue.destinationViewController as UITabBarController
        let destinationViewController = barViewControllers.viewControllers![2] as ProfileController
        destinationViewController.firstName = self.firstName
        destinationViewController.lastName = self.lastName
    }
}

When I try to set the destinationViewController (on the second line in the code above), my code crashes. I'm not sure why as I've looked on numerous StackOverflow posts such as

Swift tab bar view prepareforsegue and Pass data from tableview to tab bar view controller in Swift. but have not have much success. Do I possibly need to create a UITabBarControllerDelegate class and pass information through that? Any tips would be appreciated. Thanks!


Solution

  • The problem, as discovered after a discussion, was that the tab bar controller's children were embedded in navigation controllers, so the code needed to be changed to this,

    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { 
        let barViewControllers = segue.destinationViewController as! UITabBarController 
        let nav = barViewControllers.viewControllers![2] as! UINavigationController 
        let destinationViewController = nav.topviewcontroller as ProfileController 
        destinationViewController.firstName = self.firstName
        destinationViewController.lastName = self.lastName 
    }