Handling Players’ State Changes in Multiplayer Games
Problem
You want to detect when players in multiplayer mode get disconnected while playing the game.
Solution
Implement and handle the match:player:didChangeState: delegate message
of the GKMatchDelegate class.
Discussion
In a multiplayer game, it is important for each player to know the state of the other players in the game. The state in this case could be either connected or disconnected. Let’s take a look at an example.
Suppose you’ve written a racing game and you’ve incorporated matchmaking (see Supporting Multiplayer Games and Matchmaking). Two players connect to each other and start playing the first lap in a tournament. The game is going well until player #2 gets disconnected. At this point, player #1 must be notified by the game that player #2 has been disconnected. The game could then end the match for player #1 and start listening for other invites.
In order to get notified of changes in state of players in a
match, implement and handle the match:player:didChangeState: delegate message
of the GKMatchDelegate class. The
player parameter will contain the
player ID whose state has changed, while the didChangeState parameter, which is of type
GKPlayerConnectionState, will contain
one of the following values:
GKPlayerStateUnknownThe player’s state is unknown at the moment. In a racing game for instance, you might want to temporarily hold this player’s car position motionless on the map while the player is in an unknown state.
GKPlayerStateConnected ...