Here is a simple demo on how to use “NSNotificationCenter” in swift.

NSNotificationCenter is particularly useful when there are multiple class or struct instances that need to take action based on something that happens elsewhere in your application.

To Register the notification… we will call

 NSNotificationCenter.defaultCenter().addObserver(self, selector: "updateOnNotification", name: notificationKey, object: nil)

Now to trigger the notification…

 @IBAction func broadcastNotification(sender: UIButton){
    NSNotificationCenter.defaultCenter().postNotificationName(notificationKey, object: self)
}

//This will be triggered once the notification is sent.
func updateOnNotification() {
    println("Notification Sent");
}

The “notificationKey” should be unique for each notification to identify different broadcasts.

for eg : let notificationKey = “notification_key”

IMPORTANT NOTE : A notification observer will be removed once you close a ViewController in which it is added. i.e an observer will be removed once dealloc is called from a ViewController. In Swift it is by default.

Please leave your valuable comments below.

 

Leave a Reply

Your email address will not be published. Required fields are marked *

 

 

 

Theme by HermesThemes

Copyright © 2018 CoderzHeaven. All Rights Reserved

Please wait...

Subscribe to our newsletter

Want to be notified when our article is published? Enter your email address and name below to be the first to know.