I recently started developing my first App in Swift, and am trying to leverage NotificationCenter to communicate changes from a data management class to my ViewControllers. I am adding an observer for a specific notification name in viewWillAppear:animated, making a call to remove the observer in viewWillDisappear:animated, but for some reason the observers are just piling up as I switch from to another ViewController and come back (to the one with observers).
Here is the code I have in viewWillAppear that adds the observer:
override func viewWillAppear(_ animated: Bool)
{
super.viewWillAppear(animated)
let nc = NotificationCenter.default
nc.addObserver(forName: Notification.Name(rawValue: "SyncFinished"), object: nil, queue: nil, using: viewDidReceiveNotification)
}The code in viewWillDisappear that should be removing it:
override func viewWillDisappear(_ animated: Bool)
{
super.viewWillDisappear(animated)
let nc = NotificationCenter.default
nc.removeObserver(self, name: Notification.Name("SyncFinished"), object: nil)
}And my callback that is fired when a notification is received:
func viewDidReceiveNotification(notification: Notification) -> Void
{
if (notification.name.rawValue == "SyncFinished")
{
print("Notification Received")
}
}Can anyone spot what the issue might be? Any help would be appreciated!