Swift — NSNotificationCenter

What is “NSNotificationCenter”

NSNotificationCenter isn’t new function, there is used to notify when an event occurs. Like delegate but “NSNotificationCenter” is broadcast(one-to-many). NSNotificatinoCenter look like a radio tower. When you need to notify to receiver(other view controller), NSNotificationCenter is the best choice to solve this. In below, I will show you about “How to simple used NSNotificationCenter in swift”.

There are two sides; sender and receive. First, sender will use method “post”. It mean, notify to other places. Writing some code like this;

NSNotificationCenter.defaultCenter().postNotificationName(“NSNotificationIdentifier”, object: self) 

Finally, receiver that use “addObserver” like this;

NSNotificationCenter.defaultCenter().addObserver(self, selector: “methodOfReceivedNotification”, name:”NSNotificationIdentifier”, object: nil)
Look Out!! NSNotificationIdentifier is match with “string” so you must carefully about this. If the notificationIdentifier didn’t matching, NSNotificationCenter will fail.

Get some example of NSNotificationCenter

Looking at “Page One (ViewControllerOne)”, there is “Noti!!!!” button on the center of page. The label in other pages are change to “I’m here I receive Noti!!” when we tap on button. It is the target in this story.

First of all, Page one is a sender so we will write some code about “post” method. Creating “@IBAction” function and fill postNotification medthod.

On above, imagine that we installed radio tower and it will notify(post) to other pages when we tap on button. Now, the sender is attend.

Second, The other pages such as “page two(ViewControllerTwo)”, “page three(ViewControllerThree)” and “page four(ViewControllerFour)”, there are receiver so “addObserver” is usually method for them. In every pages, defining text label and writing method to receive notification from sender.

Now, receiver is complete. When tap button on page one, other pages that assign “addObsever’ method will receive notify and doing something in selector(receivedNotification function).

Finally, don’t forget “NotificationIdentifier”. Make sure, post and addObserver method are matching. There are a little trick to prevent this warning. Using global variable, create swift file and define variable name “notiIdentifier”.

let notiIdentifier: String = “notificationIdentifier”

Then, change all “notificationIndentifier” to notiIdentifier. OK, it will safety. If we need to change notificationIdentifier, we just change notiIdentifier that global variable string.

If you reading at this. Congratulations, NSnotificationCenter is just easy and very simple for you.

You can download project example that “https://github.com/famesprinter/NSNotificationCenterLAB”. Hope it help, thank you :D