Authenticating the Local Player in Game Center

Problem

You know that the first step to using Game Center functionalities is to authenticate the local player, but you have no idea how you should do that.

Solution

Use the authenticateWithCompletionHandler: instance method of the GKLocalPlayer class, as shown in the Discussion section.

Discussion

In Game Center, everything depends on the simple ability to access the local player. The local player is the player that is authenticated into Game Center either through the Game Center app on an iOS device or through an iOS app that utilizes Game Center. If the player has not authenticated herself yet, attempting to retrieve the local player will prompt the player to authenticate first. If the player cancels, we will get an error back in our code. If the player has already authenticated, she won’t be prompted to log into Game Center again. So long as she is authenticated, we will be able to retrieve her player object.

Every player in Game Center is represented with an object of GKPlayer. The local player is also a player, but is represented with an object of type GKLocalPlayer, a subclass of the GKPlayer class. In order to retrieve a reference to the local player object, you can use the localPlayer class method of the GKLocalPlayer class like so:

GKLocalPlayer *localPlayer = [GKLocalPlayer localPlayer];

After you have the local player’s object, you must, as soon as you have the ability to do so (right after your application loads), authenticate the ...

Get Writing Game Center Apps in iOS now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.