Broadcasts
NotificationCenter represent a notification dispatch mechanism that enables the broadcast of information to registered observers.
Notification represents a container for information broadcast through a notification center to all registered observers.
1. Define names for your notifications.
extension Notification.Name {
static let didReceiveData = Notification.Name("didReceiveData")
// ...
static let didCompleteTask = Notification.Name("eventNameX")
}
2. Register an observer.
NotificationCenter.default.addObserver(self, selector: #selector(onDidReceiveData(_:)), name: .didReceiveData, object: nil)
nc.addObserver(self, selector: #selector(onDidReceiveData(_:)), name: Notification.Name("some_new_notification_name"), object: nil)
The fourth parameter object is an optional object whose notifications you want to receive. If you set it, you’ll only receive notifications from that sender.
Typically you will register observing in the viewDidLoad() or viewWillAppear() methods of view controller.
From IOS 9 you don't need to unregister an observer.
3. Define handler of notification. In our case onDidReceiveData() method.
@objc func onDidReceiveData(_ notification: Notification) {
// .. do something
if let dict = notification.userInfo as NSDictionary? {
// .. do something with custom data
}
}
4. Post a notification, from somewhere in the app.
NotificationCenter.default.post(name: .didReceiveData, object: nil)
// post a notification with userInfo (i.e. extra custom data)
NotificationCenter.default.post(name: NSNotification.Name(rawValue: "notificationName"), object: nil, userInfo: dictionaryWithCustomData)
Before swift 3, NS* types are used: NSNotificationCenter, NSNotification.