NotificationCenter in swift

A notification dispatch mechanism that enables the broadcast of information to registered observers.
—–Apple

NotificationCenter in Swift is a mechanism for broadcasting information within a program. It allows objects to communicate with each other without needing to directly reference each other, which helps in maintaining a loose coupling between components. Here’s an overview of NotificationCenter and how to use it:

Key Concepts

  1. NotificationCenter:
    • A centralized hub through which notifications are broadcasted and received.
    • Instances of NotificationCenter are responsible for managing the registration of observers and the posting of notifications.
  2. Notification:
    • An object that encapsulates information that is broadcasted by a notification center.
    • Notifications can carry additional information through a userInfo dictionary.
  3. Observer:
    • An object that registers itself to receive notifications of a specific type.
  4. Name:
    • Notification.Name(“com.user.register.success”)
    • This is the Notification key and this should be unique for any new Notification register method. For calling the same method this should be the same. This key only can call this same method which we have registered as a key and lock .

Posting Notifications

To post a notification, use the post method on the NotificationCenter instance. You can post notifications with or without additional information.

// Without additional information
NotificationCenter.default.post(name: Notification.Name("com.user.register.success"), object: nil)

// With additional information
let userInfo: [String: Any] = ["key": "value"]
NotificationCenter.default.post(name: Notification.Name("com.user.register.success"), object: nil, userInfo: userInfo)

Adding Observers

To observe notifications, use the addObserver method. You can specify the notification name and the action to take when the notification is received.

// Adding an observer
NotificationCenter.default.addObserver(self, selector: #selector(handleNotification(_:)), name: Notification.Name("MyNotification"), object: nil)

// The method that handles the notification
@objc func handleNotification(_ notification: Notification) {
    if let userInfo = notification.userInfo {
        // Process userInfo if needed
    }
    // Handle the notification
}

Removing Observers

It is essential to remove observers when they are no longer needed to avoid memory leaks.

// Removing an observer
NotificationCenter.default.removeObserver(self, name: Notification.Name("com.user.register.success"), object: nil)

Example

Here’s a complete example demonstrating how to post and observe notifications:

import UIKit

class PostViewController: UIViewController {
    override func viewDidLoad() {
        super.viewDidLoad()
        
        // Post a notification after 2 seconds
        DispatchQueue.main.asyncAfter(deadline: .now() + 2) {
            NotificationCenter.default.post(name: Notification.Name("com.user.register.success"), object: nil, userInfo: ["message": "Hello, World!"])
        }
    }
}

class ObserveViewController: UIViewController {
    override func viewDidLoad() {
        super.viewDidLoad()
        
        // Add observer for the notification
        NotificationCenter.default.addObserver(self, selector: #selector(handleNotification(_:)), name: Notification.Name("com.user.register.success"), object: nil)
    }
    
    @objc func handleNotification(_ notification: Notification) {
        if let userInfo = notification.userInfo, let message = userInfo["message"] as? String {
            print("Received message: \(message)")
        }
    }
    
    deinit {
        // Remove observer when the view controller is deallocated
        NotificationCenter.default.removeObserver(self, name: Notification.Name("com.user.register.success"), object: nil)
    }
}

In this example, the PostViewController posts a notification after a delay, and the ObserveViewController listens for that notification and handles it when received. The observer is also removed in the deinit method to prevent memory leaks.

Extension Of Notification:

extension Notification.Name {
    static var loginSuccess: Notification.Name { 
          return .init(rawValue: "com.user.login.success") }
    static var registerSuccess: Notification.Name { 
          return .init(rawValue: "com.user.register.success") }
}

Use Case –

Now in place of NSNotification.Name(“com.user.login.success”) of you can write simply .loginSuccess

NotificationCenter.default
                  .addObserver(self,
                   selector:#selector(loginSuccess(_:)),
                   name: .loginSuccess,
                   object: nil)

How to use Object in NotificationCenter?

import UIKit

class PostViewController: UIViewController {

private let notificationCenter = NotificationCenter.default

    override func viewDidLoad() {
        super.viewDidLoad()
        
        // Post a notification after 2 seconds
        DispatchQueue.main.asyncAfter(deadline: .now() + 2) {
            notificationCenter.post(name: .loginSuccess, object: nil, userInfo: ["message": "Hello, World!"])
        }
    }
}

class ObserveViewController: UIViewController {

private let notificationCenter = NotificationCenter.default

    override func viewDidLoad() {
        super.viewDidLoad()
        
        // Add observer for the notification
        notificationCenter.addObserver(self, selector: #selector(handleNotification(_:)), name: .loginSuccess, object: nil)
    }
    
    @objc func handleNotification(_ notification: Notification) {
        if let userInfo = notification.userInfo, let message = userInfo["message"] as? String {
            print("Received message: \(message)")
        }
    }
    
    deinit {
        // Remove observer when the view controller is deallocated
        notificationCenter.removeObserver(self, name: .loginSuccess, object: nil)
    }
}
@objc func loginSuccess(_ notification: Notification){ 
print(notification.object as? [String: Any] ?? [:])
print(notification.userInfo?["userInfo"] as? [String: Any] ?? [:]) }

Refferences:

https://developer.apple.com/documentation/foundation/notificationcenter
https://medium.com/@nimjea/notificationcenter-in-swift-104b31f59772
https://reintech.io/blog/mastering-swift-notification-center#
https://chatgpt.com/c/3da0f38f-13e8-4264-82f1-79ec08800330

11 thoughts on “NotificationCenter in swift

Leave a Reply

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