how to use notificationcenter in swift

How to use notificationcenter in swift

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.

How Notification Center Works
We’ll start with how NotificationCenter exactly works. It has three components:

A “listener” that listens for notifications, called an observer
A “sender” that sends notifications when something happens
The notification center itself, that keeps track of observers and notifications

Here’s how you register an observer:

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

Here is How you post your notifications with unique Notification Name

Every Notification is defined with a unique identifier name , just like below we do

It’s common to register and remove observers in either:

viewDidLoad() and dealloc, or
viewWillAppear(_:) and viewWillDisappear(_:)