swiftpropertiesviewcontrollertabbarcontroller

Pass data from tabBarController to uiviewcontroller embedded in navigationcontroller


I have a custom tab bar controller. each tab contains a viewcontroller embedded in a navigation controller. I get a value for pro_user from the database in appledelegate and set it there. then before CustomTabBarController gets launched (in appledelegate), i set it's "pro_user" property to true or false (this works and CustomTabBarController receives the value from appledelegate).

Now i'm trying to pass this same value to the ViewControllers (ViewController1 and ViewController2). each view controller also has a "pro_user" property.I'm doing this by creating the viewcontroller instances and then setting their pro_user property before embedding each viewcontroller in a navigationcontroller. but neither viewcontroller is actually receiving the value of pro_user which i'm setting in CustomTabBarController. I hope this is clear. How do i pass the value of pro_user from CustomTabBarController to each of the view controllers? programmatically (i'm not using storyboards)

class AppDelegate: UIResponder, UIApplicationDelegate {

    var pro_user = true

    var window: UIWindow?

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions:
        [UIApplicationLaunchOptionsKey: Any]?) -> Bool {


        window = UIWindow(frame:UIScreen.main.bounds)
        window?.makeKeyAndVisible()

        let customTabBarController = CustomTabBarController()
        customTabBarontroller.pro_user = pro_user
        self.window?.rootViewController = customTabBarController

        return true

    }

}




class CustomTabBarController:UITabBarController{

    var pro_user : Bool?

    override func viewDidLoad(){
        super.viewDidLoad()


        let viewController1 = ViewController1() 
        viewController1.pro_user = pro_user //doesn't work
        let firstNavigationController = UINavigationController(rootViewController: viewController1)

        let viewController2 = ViewController2() 
        viewController2.pro_user = pro_user //doesn't work
        let secondNavigationController = UINavigationController(rootViewController:viewController2)


        viewControllers=[firstNavigationController,secondNavigationController]

}

Solution

  • It looks like you're setting a global setting. If so you may want to consider using UserDefaults.

    E.g. with a nice extension:

    extension UserDefaults {
        var isProUser: Bool {
            get {
                return bool(forKey: "isProUser")
            }
            set {
                set(newValue, forKey: "isProUser")
            }
        }
    }
    

    Then anywhere in your app you can set it:

    UserDefaults.standard.isProUser = true
    

    And get it:

    let isProUser = UserDefaults.standard.isProUser
    

    The value is also saved between launches.