UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

SOLVED: Why is NotificationCenter.default not working with Coordinators and StateMachine

Forums > Swift

I am working on a card game, using a MainCoordinator (2 other coordinators that are irrelevant here) and a state machine with 14 states, and trying to navigate using NotificationCenter.default, but my observers are not catching the messages I post. There are 4 player positions, which I call Left, Up, Right, and Down. I am only showing the code for the Left player, to simplify and shorten.

In MainCoordinator.swift, I have:

class MainCoordinator: Coordinator {
    var childCoordinators = [Coordinator]()
    var navigationController: UINavigationController
    let stateMachine: MyStateMachine
    var nc = NotificationCenter.default

    init(navigationController: UINavigationController) {
        self.navigationController = navigationController
        stateMachine = MyStateMachine(navController: navigationController, states: [...,PlayerLeftTurnState(),...])
    }

    func start() {
        let vc = ViewController.instantiate()
        vc.coordinator = self
        if navigationController.topViewController != vc {
            navigationController.pushViewController(vc, animated:false)
        }

    }

    func subscribeToNotifications() {
        nc.addObserver(self, selector: #selector(PlayerLeftTurnNotification), name: Notification.Name("playerLeftTurnNotification"), object: nil)
}

    @objc func PlayerLeftTurnNotification(notification: NSNotification) {
      stateMachine.enter(PlayerLeftTurnState.self)
    }

After I do my setup and deal the cards (in a Game.swift class), I try to post for the left player to take a turn

    var nc = NotificationCenter.default
    nc.post(name: Notification.Name("playerLeftTurnNotification"), object: nil)

This notification is not caught.

I tried adding a button to my main window, and having the IBAction post the same notification, but that is not caught either.

Any help greatly appreciated. Bill

2      

You set up your notification observer in the subscribeToNotifications function, but you don't call that function anywhere. So the observer never gets added.

2      

Hacking with Swift is sponsored by Essential Developer

SPONSORED Join a FREE crash course for mid/senior iOS devs who want to achieve an expert level of technical and practical skills – it’s the fast track to being a complete senior developer! Hurry up because it'll be available only until April 28th.

Click to save your free spot now

Sponsor Hacking with Swift and reach the world's largest Swift community!

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.