Reputation: 404
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.
Upvotes: 0
Views: 1389
Reputation: 17844
Your problem lies in the sequence of events.
When post
is called before addObserver
, there is no place for the OS to deliver the notification to, and therefore the notification is discarded.
You need to make sure that you have an active observers, i.e. that addObserver
is called before you do your `post.
Upvotes: 0
Reputation: 77423
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
}
}
Upvotes: 0