I have a notification center call that looks like this, and I’m trying to create an observer for it, which just calls a function in the same Swift file:
NotificationCenter.default.post(
name: Notification.Name(rawValue: "JSON"),
object: [ "json" : "[email protected]" ])
NotificationCenter.default.addObserver(self,
selector: #selector(receiveJsNotification(_:)),
name: NSNotification.Name ("JSON"), object: nil)
then later in my Swift file, I have:
@objc
func receiveJsNotification(_ notification: Notification) {
print("received notification");
// how do I retrieve [email protected] value?
}
However "received notification" is never printed, even though the "post" and "addObserver" lines (which I have in separate functions of the same class) are definitely executed (print statements show).
My Swift builds without error. I’m using Xcode 14.2
What am I doing wrong? Also, how do I retrieve the "[email protected]" value?
2
Answers
I’m not sure why your code doesn’t work. I just banged out an example project using the default iPhone application template (using Storyboards)
Here is the code for the ViewController class:
When I wire up the IBAction of that code to a button, run the app, and tap the button, I see a "Notification received" message appear on the console, telling me it works
Obviously this is an incredibly naive example that sends a notification to the same object (The view controller) that listens for it, but it proves that the notification center works.
To made your code work pass the data in userinfo instead of object like on below line, Also make sure your addObserver code runs before posting the notification.
In your
receiveJSNotification()
add the following codenotification object you received in function has the userInfo dictionary which holds the data you passed when calling the observer. You can get the data from dictionary and unwrap using
if let/guard let