Behrouz Riahi
Behrouz Riahi

Reputation: 1791

How to pass data to UITabBarController?

How do I pass data from UIViewController to one of the UIViewController's inside UITabBarController?

The following didn't work:

let hospitalsController = segue.destination as! postRequest
hospitalsController.hospitalName = "Hospital Name"

when trying above code, I get the following error:

Could not cast value of type 'UITabBarController' (0x10d05f418) to 'ProjectName.postRequest' (0x10b17fdd0).

when I tried the following:

let test = self.tabBarController?.viewControllers![0] as! UINavigationController
            let test2 = test.topViewController as! postRequest
            test2.hospitalName = "Khola Hospital"

The app crashed with no error,

when I tried to print print(tabBarController?.viewControllers) it showed me nil in the console

What is the correct way to pass data from UIViewController to one of the UIViewControllers inside UITabBarController?

UPDATE Here is my main storyboard StoryBoard

The data is to be passed from he top UIViewController to the bottom right UIViewController

Upvotes: 0

Views: 1702

Answers (2)

Nirav D
Nirav D

Reputation: 72410

You are too closed to make it work only one mistake you need to cast segue.destination to UITabBarController and you all set to go.

if let tabbarController = segue.destination as? UITabBarController, 
   let postVC = tabbarController.viewControllers?.first as? postRequest, 

     postVC.hospitalName = "Khola Hospital"
}

Upvotes: 1

Syed Qamar Abbas
Syed Qamar Abbas

Reputation: 3677

Create your custom UITabBarController class and pass the data to that tabBarController and then in your desired ViewController where you want to get hospital name just check the availability of tabBarController and fetch the hospital name

class YourCustomTabBarController: UITabBarController {
    var hospitalName = ""
    //Do You Other Work Below
}

class PostRequest: UIViewController {
    var hospitalName = ""
    override func viewDidLoad() {
        super.viewDidLoad()
        if let tabBarVC = self.tabBarController as? YourCustomTabBarController {
            self.hospitalName = tabBarVC.hospitalName
        }
        //Handle Other Work.
    }
}


if let tabBarVC = segue.destination as? YourCustomTabBarController {
    tabBarVC.hospitalName = "XYZ Hospital"
}

Upvotes: 0

Related Questions