Search code examples
swiftuitabbarcontrolleruserdefaults

Persist and retrieve UserDefaults between VC in a UITabbar


I have a TabBar app with 3 VCs. The first one displays a UIPickerView thatallows the user to select one of three languages, and label texts are translated depending on the language chosen. I persisted the chosen language with UserDefaults, no big deal, but when I enter the second VC the labels are not translated. If I close the App and reopen it the changes occur, so the chosen language effectively persists and is retrieved. I am using Swift 4 with Xcode 9. THANKS!


Solution

  • The tabbar instantiates all of the childview controllers when it loads, so your second VC has the language thats set at the time that the Tabbar loads, not at the time that you set it in the first view controller. You should post a notification when you change the language and listen for the notification in VC two and then update VC two accordingly.

    EDIT add code for NotificationCenter:

    In the VC where you set the language:

    NotificationCenter.default.post(name: NSNotification.Name("language changed"), object: self, userInfo: ["language": "en"])
    

    In the VC you want to update:

    NotificationCenter.default.addObserver(forName: NSNotification.Name("language changed"), object: nil, queue: .main) { notification in
        guard let language = notification.userInfo ["language"] else {
            return
        }
        //Do language stuff here
    }