How to auto-match via GKTurnBasedMatch

119 Views Asked by At

I'm trying to implement a turn-based GameKit game using a custom user interface. Specifically, I'm trying to create a new match with auto-matched players.

I've scoured the docs, but the only information I see is ambiguous at best.

It looks to me like the recipients property of GKMatchRequest determines whether or not auto-matching is used when the object is passed to the relevant method. Here's what the docs say about recipients:

If this property is non-nil, GameKit invites the specified players. GameKit doesn’t use automatch to fill player slots, and ignores the maxPlayers and minPlayers properties. If this property is nil, GameKit doesn’t invite any players. The default value is nil.

How can it be that setting this property to non-nil invites the specified player(s), but setting it to nil "doesn't invite any players"? It sounds to me like the only options are 1) invite specific player(s), or 2) create a match without an opponent.

I must be missing something, because this doesn't make sense.

Question: How does one go about creating a GameKit match with auto-matched players without using the default Game Center interface?

Here's what I've tried (opponent is a GKPlayer):

let theRequest = GKMatchRequest()
theRequest.minPlayers = 2
theRequest.maxPlayers = 2
theRequest.defaultNumberOfPlayers = 2
theRequest.inviteMessage = "Let's play!"
theRequest.recipients = [opponent]
theRequest.recipientResponseHandler = { playerWhoReceivedInvitation, responseToInvitation in
   //Do stuff
}
        
GKTurnBasedMatch.find(for: theRequest) { match, error in
   //Do stuff
}
1

There are 1 best solutions below

2
Fault On

when you build your request, you can differentiate between matching with a specific player vs auto-matching. if you specify theRequest.recipients = [opponent] it's the former.

match with specific player

//configure a GKMatchRequest for specific player(s)
request.recipients = [opponent]
request.inviteMessage = "Do you want to play a game?" //optional. affects the push notification

automatch with anyone

for automatching, don't set recipients but set the player numbers instead

//configure a GKMatchRequest for automatching
request.minPlayers = 2 //set number of players 
request.maxPlayers = 2

/*
optional -- set mask for automatching only as a specific role. 
for example if you have a chess game and you want to auto-match
but only play black or only play white. 
*/
request.playerAttributes = 0xFFFF0000 //mask for "i want to match as role A (black)"
request.playerAttributes = 0x0000FFFF //mask for "i want to match as role B (white)"
request.playerAttributes = 0xFFFFFFFF //mask for "i'll match with either" -- this is the default