Do not use the object parameter to transfer data. It is designed to filter notifications with the same name, but from a specific object. Therefore, if you transfer an object when you send a notification and another object when you add Observer, you will not receive it. If you pass zero, you basically turn off this filter.
Instead, you should use the userInfo parameter.
First, it’s best to define the name of the notification as an extension for Notification.Name. This approach is much safer and more readable:
extension Notification.Name { public static let myNotificationKey = Notification.Name(rawValue: "myNotificationKey") }
Message:
let userInfo = [ "text" : text ] NotificationCenter.default.post(name: .myNotificationKey, object: nil, userInfo: userInfo)
Subscribe:
override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) NotificationCenter.default.addObserver(self, selector: #selector(self.notificationReceived(_:)), name: .myNotificationKey, object: nil) }
Unsubscribe
override func viewDidDisappear(_ animated: Bool) { super.viewDidDisappear(animated) NotificationCenter.default.removeObserver(self, name: .myNotificationKey, object: nil) }
Method call:
func notificationReceived(_ notification: Notification) { guard let text = notification.userInfo?["text"] as? String else { return } print ("text: \(text)") }
source share