Process Player Turns Using an Event Listener

The GKTurnBasedEventListener protocol takes care of exchanges and match-related events for turn-based games; however, you don’t implement this protocol directly. Instead, you implement the GKLocalPlayerListener protocol, which inherits methods from the GKTurnBasedEventListener protocol. One of those methods is player(_:receivedTurnEventFor:didBecomeActive:).

The player(_:receivedTurnEventFor:didBecomeActive:) method gets called when it’s the local player’s turn. This method also gets called when:

  • The current player’s turn time-out is about to expire.
  • The player accepts an invite from another player.
  • The player’s turn was passed to another player.
  • The match data is saved by another player.
  • The player receives a reminder about his or her turn.

As you did with the other Game Center–related actions, you’ll use a custom notification to help process this turn event.

You’ll start by adding a new custom notification.

Setting up a Custom Turn Event Notification

Switch to the GameKitHelper.swift file. At the bottom of the file, in the Notification.Name extension, add a new custom notification:

 static​ ​let​ receivedTurnEvent = ​Notification​.​Name​(​"receivedTurnEvent"​)

Next, just above the Notification.Name extension, add a new GameKitHelper extension:

 extension​ ​GameKitHelper​: ​GKLocalPlayerListener​ {
 func​ ​player​(_ player: ​GKPlayer​,
  receivedTurnEventFor match: ​GKTurnBasedMatch​,
  didBecomeActive: ​Bool​) {
 
  matchmakerViewController?.​dismiss​(animated: ​true​, completion: ​nil​)
 NotificationCenter​.​default​.​post​(name: .receivedTurnEvent,
  object: match)
  }
 }

Here, you’re implementing the GKLocalPlayerListener protocol and its corresponding player(_:receivedTurnEventFor:didBecomeActive:) method. Inside this method, you’re dismissing the matchmakerViewController view controller and posting your new custom notification.

Now, you just need to register the listener so that you can receive these turn events.

Registering the Listener

Still inside the GameKitHelper.swift file, find the authenticatePlayer() method, and above the line that reads if error != nil {, add the following code to register the listener:

 else​ ​if​ ​GKLocalPlayer​.local.isAuthenticated {
 GKLocalPlayer​.local.​register​(​self​)
 }

To register a listener, the local player must already be authenticated. Once authenticated, you’re passing in a reference of self, indicating that the GameKitHelper class will act as the GKLocalPlayerListener object.

With your listener in place, you’re ready to get into the nitty-gritty of match data.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset