Search code examples
iosnotificationcenter

NotificationCenter.default.addObserver is not calling the objective C function


I am using swift 5 on Xcode 11.0, trying to pass a userInfo from view-controller-A to view-controller-B and I already made a notification center post in view-controller-A and here is the code:

 let uid = response["session-id"] as? String

                NotificationCenter.default.post(
                    name: NSNotification.Name("didReceiveSession"),
                    object: nil,
                    userInfo: ["uid" : uid!]
                )

And in view-controller-B I registered the notification and added an observer like so:

  NotificationCenter.default.addObserver(
            self,
            selector: #selector(self.getSessionId),
            name: NSNotification.Name("didReceiveSession"),
            object: nil
        )

And here is getSessionId:

 @objc func getSessionId(_ notification: Notification)
    {
        if let data = notification.userInfo as? [String: String]
        {
            self.session_Id = data["uid"]
        }
    }

I tried a lot of workarounds like:

1- Change name: NSNotification.Name("didReceiveSession") to name: NSNotification.Name(rawValue: "didReceiveSession") in both view controllers

2- Create an instance in view-controller-A:

2.1- share = view-controller-A()

2.2- Change object: nil to object: view-controller-A.share in the addObserver (view-controller-B)

3- Change the selector in view-controller-B from selector: #selector(self.getSessionId) to selector: #selector(getSessionId(_:))

But unfortunately, all attempts did not work. I can't figure out what's wrong.


Solution

  • This is a very incorrect way to use Notifications.

    What you want to do is pass your "sessionID" value to from VC-A to VC-B when VC-A is moving to / presenting VC-B.

    Assuming you are using a segue...

    Based on what you posted, you already have a variable / property in VC-B, probably:

    var session_ID: [String] = ""
    

    So, in VC-A, you would do something like this:

    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if let nextVC = segue.destination as? VCB {
            nextVC.session_ID = self.uid
        }
    }