Search code examples
swiftnsnotifications

Swift NSNotification Observers not working


I have 2 view controllers, one with a switch that when toggled should post the following notification. In the other view controller I have Observers which should trigger the following function which just toggles a boolean. I am not able to get the observers to work and make that function call, am I doing something wrong here? I have another Notification (Doesn't trigger with user input) that is being sent in the opposite direction which works fine.

    @IBAction func switchAction(_ sender: Any) {
    if switchUI.isOn {
        print("Collecting Data ")
        NotificationCenter.default.post(name:NSNotification.Name(rawValue: "Collect"), object: self)
    }
    else
    {
        print("Not Collecting Data")
        NotificationCenter.default.post(name:NSNotification.Name(rawValue: "Do Not Collect"), object: self)
    }
}

    func collectDataObserver () {
    //Add an Observer
    NotificationCenter.default.addObserver(self, selector: #selector(CentralViewController.toggleData(notification:)), name: Notification.Name(rawValue: "Collect"), object: nil)
    NotificationCenter.default.addObserver(self, selector: #selector(CentralViewController.toggleData(notification:)), name: Notification.Name(rawValue: "Do Not Collect"), object: nil)
}

@objc func toggleData(notification: NSNotification) {
    let isCollectData = notification.name.rawValue == "Collect"
    if(isCollectData){
        IsCollectingData = true
    }
    else
    {
        IsCollectingData = false
    }
}

Solution

  • You need to call collectDataObserver() in viewDidLoad() of CentralViewController, i.e.

    override func viewDidLoad() {
        super.viewDidLoad()
        collectDataObserver()
    }