skip to Main Content

I’m currently trying to open a modally presented ViewController when pushing a button and send some Data to this modally ViewController by a Notification. The problem is that the NotificationObserver seems not to be working on the modally presented ViewController.

This is how I push the Notification:

let scores = ["Bob": 5, "Alice": 3, "Arthur": 42]
        
NotificationCenter.default.post(Notification(name: .didReceiveData, object: self, userInfo: scores))

This is how I add the Observer

NotificationCenter.default.addObserver(self, selector: #selector(self.onDidReceiveData(_:)), name: .didReceiveData, object: nil)

@objc func onDidReceiveData(_ notification:Notification) {
    if let data = notification.userInfo as? [String: Int]
        {
            for (name, score) in data
            {
                print("(name) scored (score) points!")
            }
        }
}

I’ve already tried adding the NotificationObserver both in viewDidLoad and viewWillAppear, but both options did not work for me.

Does anybody have a solution for this kind of problem?

(I’m using Xcode 12.1, and deploying it on IOS 14.1)

2

Answers


  1. Chosen as BEST ANSWER

    Thanks for an answer Andrew, I just solved the issue by refusing the use of Notifications.

    In the prepare function for the StoryboardSegues, i created an instance to the ViewController I'm sending the user to and manipulated a variable in the others ViewControllers class by this instance.

    let destinationViewController = segue.destination as! OtherViewController
    
    destinationViewController.variable = someContent
    

  2. First make sure that you subscribe first and only after send a notification. Try to set few breakpoints and check your subscribe / post flow correct.

    Also, as for me, more accurate way to pass data is using viewController’s properties.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search