Search code examples
iosswiftuitabbarcontrolleruitabbar

How to pass data between View Controllers in UITabBarController?


I have two questions. I want to pass data. I have two ViewControllers. Controller A has Data and I want to pass it from A to B controller.

First - tab bar controller has a relationship segue. Can I use this? E.g.: perform segue or prepare?

Second - I want to pass data between ViewControllers in UITabBarController I can't do this. I searched this I can't find this...

I don't know if the search word is wrong. Can you tell me how to do it or how to search for it?


Solution

  • No, You can not pass the data between two ViewController directly, if they are connected to TabbArController.

    If you want you can manage through NotificationCenter (So when a new change occur and you post the notification, it will automatically refresh the data)

    NotificationCenter.default.addObserver(
                self,
                selector: #selector(self.getData),
                name: .refreshAttendanceForSelectedDate,
                object: nil)
    
    @objc func getData() {
    /// perform task in view controller
    }
    

    // post the changes when you get response ....

    NotificationCenter.default.post(name: Constants.Notification.refreshAttendanceForSelectedDate, object: nil)
    

    Or You can pass the updated data by DataStorgae in a variable of that respective model type (LocalCache) by creating a singleton object. This variable will reside in memory till the app will reside in memory. After forcing kill the app or flush out the app from memory, this variable will automatically be removed.

    Note: If needed, please don't forget to set value nil. (Eg. on logout action)

    class DataStorage {
        
        /// Created the singleton objectbas
        static let instance = DataStorage()
        
       /// Created the properties
        var notificationbadgeCount: Int?
        var configData: ConfigurationModel?    
    }
    

    Use by set

    DataStorage.instance.selectedStaffId = model.id
    

    get the value

    if let id = DataStorage.instance.selectedStaffId {
    /// Perform respective task ....
    }