user1895268
user1895268

Reputation: 1679

Observers don't get called using NotificationCenter Swift 4.0

I have a two ViewControllers: ViewController and SecondViewController. I added an observer to this two ViewControllers. In ViewController I also defined an IBAction to post the notification. I handle the notification via a closure in both ViewControllers. But only the closure in the ViewController gets called. The closure (and even the whole code) in the SecondViewController does not get called (I checked with debugger). The closure only contains a print-statement. Here is my Code

//ViewController
import UIKit

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        let nc = NotificationCenter.default
        nc.addObserver(forName: Notification.Name(rawValue:"MyNotification"), object: nil, queue: nil) { (notification) in
            print("I'm the : \(type(of: self))")
        }
    }

    @IBAction func sendNotification(_ sender: UIButton) {
        let nc = NotificationCenter.default
        nc.post(name: Notification.Name(rawValue:"MyNotification"), object: nil, userInfo: ["message":"Hello there!", "Date:":Date()])

    }
}

The ScondViewController

//SecondViewController
import UIKit

class SecondViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        let nc = NotificationCenter.default
        nc.addObserver(forName: Notification.Name(rawValue:"MyNotification"), object: nil, queue: nil) { (notification) in
            print("I'm the: \(type(of: self))")
        }
    }
}

The closure in ViewController gets called but the closure in SecondViewController does not. Maybe the reason is that SecondViewController does not get initialized before I post the notification. But how would a solution look like? Any help is appreciated.

Upvotes: 0

Views: 536

Answers (1)

PoolHallJunkie
PoolHallJunkie

Reputation: 1363

If this is one-to-one relationship you can also use the Delegate pattern instead. Although you are right, the notification observer is not yet called because you do not initialise before the post. So there shouldn't be a reason for a function to be called in the SecondViewController.

So if you only need that to update a variable value, you can do that somewhere else in a Variables class where both ViewControllers have access.

Upvotes: 1

Related Questions