Authenticating Game Center’s Local Player in a SpriteKit Game in Swift

June 6th, 2016

Filed under: Game Development, iOS Development, Mac Development | Be the first to comment!

Authenticating the local player for Game Center in a SpriteKit game requires two steps. The first step is to call the GKLocalPlayer class method localPlayer, which gives you access to Game Center’s local player.

The second step is to supply a closure for the local player’s authenticateHandler property. This closure takes two arguments: a view controller and an error. The closure returns Void.

In the closure the first thing to check is whether or not the view controller is nil. If the view controller is not nil, present Game Center’s view controller so the player can login. The next thing to check is if the local player has been authenticated. If the local player has been authenticated, you can start using Game Center. If the player is not authenticated, don’t use Game Center. The following code shows an example of authenticating a local player in a SpriteKit scene in an iOS game using Swift:

func authenticateLocalPlayer() {
    let localPlayer = GKLocalPlayer.localPlayer()
    localPlayer.authenticateHandler = {(viewController, error) -> Void in
        if viewController != nil {
            // Show the view controller to let the player log in to Game Center.
            self.view?.window?.rootViewController?.presentViewController
                (viewController!, animated: true, completion: nil)               
        }
        else if localPlayer.authenticated {
            // You can start using Game Center
        }
        else {
            // Don't use Game Center
        }
    }
}

For a Mac game you would call the function presentViewControllerAsSheet instead of presentViewController.

The expression self.view?.window?.rootViewController? is messy, but that’s what you have to do to access the SpriteKit scene’s view controller. You need to access the scene’s view controller so you can present Game Center’s view controller.

Tags: ,


Leave a Reply

Your email address will not be published. Required fields are marked *