Broadcasting of information in iOS (NotificationCenter) iOS 30.10.2019

If you want to track any states of your app such as when a user makes a certain choice by clicking different user interface objects. In that case, you can use the notification center.

With NotificationCenter you can broadcast data from one part of your app to another. It uses the Observer pattern to inform registered observers when a notification comes in, using a central dispatcher called Notification Center.

To use the notification center, you need to follow several steps:

  • Define a unique name for each action you want to detect.
  • Define one or more notification center observers to receive notifications when certain actions occur.
  • Write functions to run when a notification center observer receives a notification.
  • Write code to send a notification when a certain action occurs.

Following extension simply defines arbitrary names that will be used to identify our different notification center observers that we’ll define next.

import UIKit
extension Notification.Name {
    static let didReceiveData = Notification.Name("didReceiveData") 
}

class ViewController: UIViewController {
    @IBOutlet var myLabel: UILabel!

    @objc func onDidReceiveData(notification: Notification) { 
        myLabel.text = "didReceiveData"

        if let data = notification.userInfo as? [String: Int] {
            for (name, score) in data {
                print("\(name) scored \(score) points!")
            }
        }
    }

    override func viewDidLoad() { 
        super.viewDidLoad()
        NotificationCenter.default.addObserver(self, 
            selector: #selector(onDidReceiveData(notification:)), 
            name: .didReceiveData, object: nil)
    }

    deinit {
        NSNotificationCenter.default.removeObserver(self)
    }
}

class SecondViewController: UIViewController {
    @IBAction func tapButton(_ sender: UIButton) { 
        let scores = ["Bob": 5, "Alice": 3, "Arthur": 42]
        NotificationCenter.default.post(name: .didReceiveData, object: nil, userInfo: scores)
        dismiss(animated: true, completion: nil)
    }
}