Tags
swift
Asked 4 years ago
13 Jan 2020
Views 737
iptracker

iptracker posted

how to pass data or object from one tab to another tab

i have five tabs in tab bar . and i want to transfer data or object from one tab view controller to another tab bar controller .
how can i possible send data between tab controller ?
Cimb

Cimb
answered Apr 25 '23 00:00

To pass data or objects between tabs in an iOS application, there are several approaches you can take depending on your application's requirements. Here are a few examples:

1.UserDefaults:
You can use UserDefaults to store the data and then retrieve it in the other tab. This is suitable for small amounts of data, such as user preferences or settings. Here's an example:
In the first tab:


UserDefaults.standard.set("
My Data", forKey: "myDataKey")

In the second tab:



let myData = UserDefaults.standard.string(forKey: "myDataKey") 

2.Singleton:
You can create a singleton class to store the data and access it from any tab. Here's an example:


class MyData {
    static let shared = MyData()
    var data: String?
}

// In the first tab:
MyData.shared.data = "My Data"

// In the second tab:
let myData = MyData.shared.data

Note that if you're accessing the data from multiple threads, you'll need to ensure it's thread-safe.

3.Notifications:
You can use NotificationCenter to send a notification with the data to the other tab. Here's an example:
In the first tab:



NotificationCenter.default.post(name: Notification.Name("MyNotification"), object: nil, userInfo: ["myData
": "My Data"])
In the second tab:



NotificationCenter.default.addObserver(forName: Notification.Name("MyNotification"), object: nil, queue: nil) { notification in
    let myData = notification.userInfo?["myData"] as? String
}

4.Delegates:
You can use delegates to pass the data between tabs. Here's an example:


protocol MyDataDelegate: AnyObject {
    func didReceiveData(_ data: String?)
}

class FirstTabViewController: UIViewController {
    weak var delegate: MyDataDelegate?

    func sendData() {
        delegate?.didReceiveData("My Data")
    }
}

class SecondTabViewController: UIViewController {
    override func viewDidLoad() {
        super.viewDidLoad()
        guard let firstTabVC = self.tabBarController?.viewControllers?[0] as? FirstTabViewController else { return }
        firstTabVC.delegate = self
    }
}

extension SecondTabViewController: MyDataDelegate {
    func didReceiveData(_ data: String?) {
        let myData = data
    }
}

These are just a few examples of how you can pass data or objects between tabs in iOS. You'll need to choose the approach that's best suited for your specific application.
Post Answer