Game Development Reference
In-Depth Information
To get started with Game Center, all apps must get access to an instance of GKLocalPlayer that
represents the local player and authenticate them. Listing 9-1 shows the canonical example of doing this.
Listing 9-1. RootViewController.m (initGameCenter)
-(void)initGameCenter{
Class gkClass = NSClassFromString(@"GKLocalPlayer");
BOOL iosSupported = [[[UIDevice currentDevice] systemVersion]
compare:@"4.1" options:NSNumericSearch] != NSOrderedAscending;
if (gkClass && iosSupported){
localPlayer = [GKLocalPlayer localPlayer];
[localPlayer authenticateWithCompletionHandler:^(NSError *error) {
if (localPlayer.authenticated){
[leaderBoardButton setEnabled:YES];
} else {
[leaderBoardButton setEnabled:NO];
}
}];
}
}
In Listing 9-1, we see the task initGameCenter of the class RootViewController . This task is called
once at the beginning of the application launch. It first checks to see if GameKit is available on this
iOS device by looking for the class GKLocalPlayer . The tasks also checks to see if the version of
iOS is recent enough to support Game Center. If yes, we get a pointer to the local player by calling
localPlayer on the class GKLocalPlayer .
To authenticate our local player, we simply call authenticateWithCompletionHandler : and pass a
block that will be executed asynchronously when the user has authenticated (or cancelled). A block
is simply a way of declaring a function that can be passed around as value. In this case, we are
using a block in the same way we would use an anonymous class on a language like Java. The first
time this code is run, the user will see something like Figure 9-9 .
Figure 9-9. First-time authentication with Game Center
2
 
Search WWH ::




Custom Search