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

func applicationDidBecomeActive(_ application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
NotificationCenter.default.post(name: Foundation.Notification.Name(rawValue: Notification.systemIsBusyShowIndicator), object: nil)
}

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

import Foundation
class Notification {

class var systemIsBusyShowIndicator: String {
get { return "systemIsBusyShowIndicator" }
set { return }
}
class var systemIsBusyHideIndicator: String {
get { return "systemIsBusyHideIndicator" }
set { return }
}

}

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

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

override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.

The notification names are now available as static constants on the Notification.Name type, so you can use this syntax:

// Create notification
NotificationCenter.default.addObserver(self, selector: #selector(handleSystemBusyHideIndicatorNotification(_:)),
name: NSNotification.Name(rawValue: Notification.systemIsBusyHideIndicator),
object: nil)

// Create notification
NotificationCenter.default.addObserver(self, selector: #selector(handleSystemBusyShowIndicatorNotification(_:)),
name: NSNotification.Name(rawValue: Notification.systemIsBusyShowIndicator),
object: nil)

}
@objc fileprivate func handleSystemBusyHideIndicatorNotification(_ notification: Foundation.Notification) {

//hideProgressIndicator()
}
@objc fileprivate func handleSystemBusyShowIndicatorNotification(_ notification: Foundation.Notification) {

//showProgressIndicator()
}

Discover more from mycodetips

Subscribe to get the latest posts sent to your email.

Discover more from mycodetips

Subscribe now to keep reading and get access to the full archive.

Continue reading

Scroll to Top