iosswiftnotificationcenter

NotificationCenter help for Swift - how to use addObserver?


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" : "user@domain.com" ])
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 user@domain.com 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 "user@domain.com" value?


Solution

  • This is what ended up working for me:

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
    
        NotificationCenter.default.addObserver(self, selector: #selector(receiveJsNotification(_:)),
                            name: NSNotification.Name ("JSON"), object: nil)
    
    
        // elsewhere in the app, we pass the value...
        let value = "some value";
    
        NotificationCenter.default.post(name: NSNotification.Name(rawValue: "JSON"), object: nil, userInfo: ["json" : value]) 
    
        return true
    }
    
    
    @objc
    func receiveJsNotification(_ notification: Notification) {
        let jsonValue = notification.userInfo as AnyObject?
        
        if (jsonValue !== nil) {
            let someValue = jsonValue?.object(forKey: "json") ?? ""
            // do something with someValue here
        }
    }