search by tags

for the user

adventures into the land of the command line

NSNotificationCenter

What is it? It’s like rabbitMQ, but completely internal to the app. It’s like a message queue between different parts, like a function over here and a Button over there. How can we use it?

Create a new file:

NSNotificationCenterKeys.swift

Specify one or more unique notification keys inside it:

let someNotificationKey = "com.someGroovyKey.specialNotificationKey"

Post a notification to NSNotificationCenter.default, identifying a key you have put in NSNotificationCenterKeys.swift

class FirstViewController: UIViewController {
    @IBAction func notify() {
        //Swift 3
        NotificationCenter.default.post(name: Notification.Name(rawValue: someNotificationKey), object: self)
        // Swift 2
        NSNotificationCenter.defaultCenter().postNotificationName(someNotificationKey, object: nil)
    }
}

Set up one or more class or struct instances to be listeners, or more properly, observers of a particular notification. Such an observer will be able to tell that it’s “heard” the notification, because it will be “listening for” a notification that uses the same key.

class SecondViewController: UIViewController {
    override func viewDidLoad() {
    super.viewDidLoad()
        // Swift 3
        NotificationCenter.default.addObserver(self, selector: #selector(SecondViewController.actOnSpecialNotification), name: NSNotification.Name(rawValue: someNotificationKey), object: nil)
        // Swift 2
        NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(SecondViewController.actOnNotification), name: someNotificationKey, object: nil)
    }
}

With no posts to the notification center on that station, tuning in will do no good. Likewise, posting a notification but having no listeners accomplishes nothing. when signing up to be an observer, the instance must also specify the name of a function that will be called upon receipt of the notification it’s listening for.

class SecondViewController: UIViewController {
    @IBOutlet weak var notificationLabel: UILabel!

    func actOnSpecialNotification() {
        self.notificationLabel.text = "I heard the notification!"
    }
}

One final requirement for working with NSNotificationCenter is to remove an observer when it no longer needs to listen for notifications. We should unregister as soon as we don’t need to receive notifications anymore.

deinit {
    // Swift 3
    NSNotificationCenter.default.removeObserver(self)
    // Swift 2
    NSNotificationCenter.defaultCenter().removeObserver(self)
}