create a match in gamekit in swift

To create a match using GameKit in Swift, you'll first need to authenticate the local player with Game Center, and then implement the GKMatchmakerViewControllerDelegate method to initiate a matchmaking request. Here's an example implementation:

main.swift
import GameKit

class GameViewController: UIViewController, GKMatchmakerViewControllerDelegate {

    var matchmaker: GKMatchmakerViewController?

    override func viewDidLoad() {
        super.viewDidLoad()
        authenticateLocalPlayer()
    }

    func authenticateLocalPlayer() {
        let localPlayer = GKLocalPlayer.local
        localPlayer.authenticateHandler = { viewController, error in
            if let vc = viewController {
                self.present(vc, animated: true, completion: nil)
            } else if error == nil {
                print("Local player authenticated.")
            } else {
                print("Local player authentication failed with error: \(error!.localizedDescription)")
            }
        }
    }

    func findMatch() {
        let request = GKMatchRequest()
        request.minPlayers = 2
        request.maxPlayers = 4

        matchmaker = GKMatchmakerViewController(matchRequest: request)
        matchmaker?.matchmakerDelegate = self

        if let vc = matchmaker {
            self.present(vc, animated: true, completion: nil)
        }
    }

    // GKMatchmakerViewControllerDelegate method
    func matchmakerViewControllerWasCancelled(_ viewController: GKMatchmakerViewController) {
        print("Matchmaking was cancelled.")
        dismiss(animated: true, completion: nil)
    }

    // GKMatchmakerViewControllerDelegate method
    func matchmakerViewController(_ viewController: GKMatchmakerViewController, didFailWithError error: Error) {
        print("Matchmaking failed with error: \(error.localizedDescription)")
        dismiss(animated: true, completion: nil)
    }

    // GKMatchmakerViewControllerDelegate method
    func matchmakerViewController(_ viewController: GKMatchmakerViewController, didFind match: GKMatch) {
        print("Match found!")
        dismiss(animated: true, completion: nil)
        // Handle the match object, and start the game...
    }

}
1949 chars
58 lines

In the example above, we have implemented the authenticateLocalPlayer() function, which shows the Game Center login view controller if the player is not already authenticated.

When the findMatch() function is called, it creates a GKMatchRequest object with the desired min and max number of players, and then shows a GKMatchmakerViewController to the user. The matchmakerViewController(_:didFind:) delegate method is called when a match is found, and you can handle the match object to start your game.

Note that in order to use Game Center in your app, you need to set up your app on the developer portal, and configure the appropriate entitlements and capabilities in Xcode.

gistlibby LogSnag