NSNotificationCenter addObserver in Swift


The purpose of this article is to explain how an iOS application can send and receive change events using NSNotificationCenter.

In an iOS application, you might need to send and receive events anywhere in the app. It may be useful to use the NSNotificationCenter class when you need to receive events anywhere in the app. In this case, you can listen to events and react accordingly.

NSNotificationCenter class in the Foundation framework that provides a mechanism for broadcasting notifications to registered observers. It allows objects to communicate with each other and respond to events that occur within a program.

How to Post an Event?

Syntax

NotificationCenter.default.post(name: <NSNotification.Name>, object: <Any?>, userInfo: <[AnyHashable : Any]?>)

NotificationCenter provides a post() method to send an event. To post an event, you have to pass the notification name as an identity. You can ignore the object and user info if you don't want to send any other info.

Example

Here's an example of how to use NSNotificationCenter to post a notification −

import Foundation class User { var userId: String = "" func doLogout() { // write your code to logout the user // you will send an event once the user will be logged out. For example, NotificationCenter.default.post(name: NSNotification.Name("UserLoggedOut"), object: nil, userInfo: ["userId": userId]) } }

How to Receive an Event?

Syntax

NotificationCenter.default.addObserver(<observer: Any>, selector: <Selector>, name: <NSNotification.Name?>, object: <Any?>)

NotificationCenter provides an addObserver() method to receive an event. To listen to an event, you have to add an observer to the target notification name. You will receive an object if you send one.

Example

Here's an example of how to use NSNotificationCenter to receive a notification −

import Foundation import UIKit class HomeController: UIViewController { override func viewDidLoad() { super.viewDidLoad() NotificationCenter.default.addObserver(self, selector: #selector(handleLoggedOutNotification), name: NSNotification.Name("UserLoggedOut"), object: nil) } @objc private func handleLoggedOutNotification(_ notification: NSNotification) { print("notification: \(notification)") /* {name = UserLoggedOut; userInfo = { userId = 123; }} */ } }

In this example, the User instance posts the "UserLoggedOut" notification using the post method of NSNotificationCenter. The HomeController class is registered as an observer for this notification, and its handleLoggedOutNotification method is called when the notification is received.

It's imperative to note that notifications are broadcast asynchronously, which means that the observer may not receive the notification immediately after it is posted.

Manage Your Custom Notifications

In a real application, you might need to send and receive multiple notifications with custom names. Once you post a notification, you have to pass the NSNotificationName object to identify the notification.

Example

To register your own custom notifications, we recommend you write an extension for the NSNotification.Name class and add all your related notifications to it. For example,

Import Foundation extension NSNotification.Name { static let userLoggedIn = NSNotification.Name("userLoggedIn") static let userLoggedOut = NSNotification.Name("userLoggedOut") static let userProfilePhotoChanged = NSNotification.Name("userProfilePhotoChanged") }

We are extending NSNotificationName and adding different notification names.

Now, it will be easy to provide the name while sending and receiving the notification like the below −

import Foundation func send() { NotificationCenter.default.post(name: .userLoggedOut, object: nil, userInfo: ["userId": "123"]) } func receive() { NotificationCenter.default.addObserver(self, selector: #selector(handleLoggedOutNotification), name: .userLoggedOut, object: nil) } @objc private func handleLoggedOutNotification(_ notification: NSNotification) { print("notification: \(notification)") }

NSNotification center has three overloaded methods to post notifications −

  • NotificationCenter.default.post(notification:) − Use this method if you just need to post a notification with no context whatsoever.

  • NotificationCenter.default.post(name:object:) − Use this method if you need to post a notification and care about who is posting it. The object person is the sender, the object posting the notification.

  • NotificationCenter.default.post(name:object:userInfo:) − This method is the most complete one. You specify the notification name, the object (which is again the sender), and an userInfo dictionary. You can use this dictionary to provide additional data to the observers. In our example, we can provide the picture that was just added to the app.

Conclusion

While you are using NotificationCenter class to send and receive the events, remember that they broadcast the messages in the entire application. You have to post and receive the events very carefully and only if required.

Updated on: 03-Jan-2023

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements