Using NSNotificationCenter in Swift

Joyce Matos
3 min readFeb 13, 2017

--

NSNotificationCenter can be seen as a tool for communicating information within your app. Unlike push or local notifications where you are notifying a user of any content you would like them to receive, NSNotificationCenter allows us to send and receive information between classes and/or structs based on an action that has occurred in our app.

To put it simply, NSNotificationCenter can be thought of as a broadcaster and we can tune into different stations, or channels to listen for any changes.

NotificationCenter.default is where all notifications are posted to and are observed from. Each notification must have a unique way to identify themselves, which would then represent the channel we are tuning in to if we continue with our analogy. In this same way, if we were to observe, or listen, to any channel, we would call on the observe method available to us through NotificationCenter.default and perform some type of action based on this listening.

I’ve created a simple app that demonstrates the use of NSNotifcationCenter so that we can better understand what this would look like in code, and how it actually works. If you’re like me and you’re a hands on type of learner — feel free to code along.

ChooseDestinationVC and DestinationVC

In this app I’ve embedded a navigation controller and hooked up any IBOutlets and IBActions needed. The goal of this app is to display the name of the destination chosen when it has been selected from a different view controller.

To begin we will start by creating actions that will be performed whenever NotificationCenter has detected a change within a given channel.

In our case, we are creating two functions that will change the city label in our ChooseDestinationVC.

func setToPeru(notification: NSNotification) {     cityChosenLabel.text = "Peru"}func setToArgentina(notfication: NSNotification) {     cityChosenLabel.text = "Argentina"}

Each function will set the cityChosenLabel to it’s corresponding text. We won’t be doing anything with these functions yet, but soon we will call on them when we begin to observe in our app.

Remember when I mentioned that each notification should have a unique identity? Well, I’ve created an extension on Notification.Name and added two static properties with the name of each channel. Normally you can manually type in the string containing the name you would like to use for your notification when you call on the observe or post methods, but this helps us steer away from bugs and leaves less space for errors due to misspellings.

extension Notification.Name {     static let peru = Notification.Name("peru")
static let argentina = Notification.Name("argentina")
}

Afterwards we will add observation methods in our ViewDidLoad that will listen to their designated channels and perform actions based on each one.

NotificationCenter.default.addObserver(self, selector: #selector(setToPeru(notification:)), name: .peru, object: nil)NotificationCenter.default.addObserver(self, selector: #selector(setToArgentina(notfication:)), name: .argentina, object: nil)

Our first observer method will perform the function we created above, setToPeru(notification:), where we change the label’s text in the event that a notification has been posted to the .peru channel. The same is then applied to the function that listens for and changes the label’s text to Argentina, setToArgentina(notification:).

From here we move on to our next view controller, DestinationVC. Here we will post a notification when someone clicks on either button.

@IBAction func peruButton(_ sender: Any) {     NotificationCenter.default.post(name: .peru, object: nil)}@IBAction func argentinaButton(_ sender: Any) {     NotificationCenter.default.post(name: .argentina, object: nil}

We will post a notification to the .peru channel if a user clicks on the peruButton, and the same will apply for the argentinaButton with it’s respective channel.

Now we can run our app and see the text in our city label change depending on what button is clicked! Although this example was a simple one, there are so many ways of using NSNotificationCenter. This can be extremely useful when one has an app that requires a user to log in and would like to perform a certain action depending on whether or not they are logged in.

Feel free to leave a comment below and let me know how you plan to use NSNotificationCenter. I’d love to hear about what you all are up to and how this can be useful for your app!

--

--

Joyce Matos

iOS Developer // Flatiron School Grad // Life long student fascinated by the unknown