Passing data from one view controller to another view controller using Notification Center is an easy way when compared to delegate protocols
.
Here we need add observer
or listeners
for getting new data to load. First we need to send data using post notification method.
Sending Data - Post Notification:
1 | let dataToSend = ["name" : "John", "age" : 25] as [String : Any] |
1 | NotificationCenter.default.post(name: NSNotification.Name(rawValue: "newDataToLoad"), object: dataToSend) |
Before sending data we need to listen for the above notification using NSNotification.Name
Data Receiving - Add observer:
Add the following code for listening
to new data:
1 | NotificationCenter.default.addObserver(self, selector: #selector(notificationRecevied(notification:)), name: NSNotification.Name(rawValue: "newDataToLoad"), object: nil) |
Add the following method to retrieve data:
1 | func notificationRecevied(notification: Notification) { |
Remove Observer:
Don’t forgot to remove observer onviewWillDisappear()
as follow:
1 | NotificationCenter.default.removeObserver(self, name: NSNotification.Name(rawValue: "newDataToLoad"), object: nil) |
Source: iosrevisited