Type Method

findMatchForRequest:withCompletionHandler:

Programmatically searches for a new match to join.

Declaration

+ (void)findMatchForRequest:(GKMatchRequest *)request withCompletionHandler:(void (^)(GKTurnBasedMatch *match, NSError *error))completionHandler;

Parameters

request

A match request that specifies the properties that the new match must fulfill.

completionHandler

A block to be called after the match is successfully created.

The block receives the following parameters:

match

A newly initialized match object that contains a list of players for the match. If an error occurred, this value is nil.

error

If an error occurred, this error object describes the error. If the operation was completed successfully, the value is nil.

Discussion

When this method is called, it creates a background task to handle the request. The method then returns control to your game. Later, when the task is complete, Game Kit calls your completion handler. The completion handler is always called on the main thread.

This method may either create a new match or it may place the player into an existing match that needs a new player to advance the match further. Regardless of how the player is placed in the match, the local player is always the current participant in the returned match. Your game should immediately display the match in its user interface and allow the player to take a turn.

To be consistent with older servers and versions of iOS, the minimum number of players specified by the GKMatchRequest object is set to be equal to the maximum number of players when looking for a match.

Listing 1 shows a trivial example of how to create your own custom match interface. It creates a new match request and then uses it to find a new match. (Typically, if your game was implementing a custom match interface, it might set other properties of the request object, such as the playersToInvite property.) If a match is found, transition to the gameplay screen.

Listing 1

Finding a turn-based match programmatically

- (IBAction)findProgrammaticMatch: (id) sender
{
    GKMatchRequest *request = [[GKMatchRequest alloc] init];
    request.minPlayers = 4;
    request.maxPlayers = 16;
    [GKTurnBasedMatch findMatchForRequest: request withCompletionHandler:^(GKTurnBasedMatch *match, NSError *error)
    {
        if (match)
            [self performSegueWithIdentifier:@"GamePlayScene" sender:match];
    }];
}

See Also

Creating a New Match

- acceptInviteWithCompletionHandler:

Programmatically accept an invitation to a turn-based match.

- declineInviteWithCompletionHandler:

Programmatically decline an invitation to a turn-based match.

- rematchWithCompletionHandler:

Create a new turn-based match with the same participants as an existing match.