Notification Center

Felicity Johnson
2 min readFeb 7, 2017

--

Notification center is a internal communication tool; it provides a way for one instance of a class/struct to notify one or more other instances about something. The notification center acts as the “broadcaster” of notifications. When you post a notification to the notification center, you identify it using a unique key. Within the class/struct instances that are waiting to receive the notification, you set up an “observer” that has the same unique key that is found in the posted notification. When creating an observer, you also specify the function that will be executed once the observer receives the message from the notification center

In the code below, there are two notifications being posted: “login-success” and “animate-label.” When the button is clicked, the “login-success” notification is posted (in sendNotification()). The observer in viewDidLoad ensures that the VC is aware that it is “observing” something. Once the “login-success” notification is posted, the observer receives the notification and executes the func written in the #selector(). So, in the example below, it runs notificationSegue().

Within notificationSegue() a SECOND notification is posted (“animate-label”). The VC that notificationSegue() segues to is called ViewController (pasted below). As you can see, this VC also has an observer, but instead of it observing “login-success,” it is waiting to receive a notification with the unique key “animate-login.” Since notificationSegue posted this observer, the minute the segue to this VC is executed, the observer receives the notification and fires off animateHelloLabel().

One thing to note about NotifcationCenter is you must remove an observer when it no longer needs to listen for notifications.

Hope this was helpful and as always, happy coding!!

--

--