Generally, people love playing games that are competitve and challenging. It has become one of the communal activity. Competetors would always love to share their high score with other participants. And this level can be achieved only, by having a universal score board through the game center

It makes a game more interesting & more addictive. We can show top 10, 100 or 1000 of scores on leaderboard  and set the achievements in game at some stages as well. Its not necessary to add Leaderboard and achievement both at a time.

Game center stores data of player & game on the server. It allows the player to send request to another players and can also ask to take up the game challenge. In this way it provides social gaming functionality.

Here are the simple steps that will help you to Integrate Game Center.

Step 1:

  • Login to your iTunes Connect account and select your app. Go to Game Center option located next to In-App Purchases & you will see the below screen.

 

login-to-itune-connect

 

  • Follow the steps and Set up Leaderboard as you required.

  • Select “Enable for Single Game” to set-up the Game Center for your Application. And you be redirected to the below page.

 

enable-for-single-game

 

  • Now Click on Add Leaderboard and you will get this page.

 

add-leaderboard

 

  • Select choose to create New Leaderboard, You will be redirected to the below  page.

 

single-leaderboard

 

leaderboard-localization

 

  • Fill all the required details & click on Save. Now Your leaderboard is ready on the iTunes to connect with your Application on Game Center.

  • Now, go to Application Metadata section where screen shots, description & keywords are added. Below the build you will get game center option.

  • By Default it will be off , on it and Select Leaderboard that you have created.

 

Coding Stuff

 

In above part we have seen the steps to set up & enable game center for the Application. Now it’s time to make a code that can connect Application with Apple’s Game center server.

Because it is iOS 8, special code will work in min iOS 6.0 to max iOS 8.0.2  and  other latest versions.To be precise, it will be compatible in all latest iOS devices.

Code to implement game center:

Step 1: Create GameKitHelper class

GamekitHelper.h


#import <GameKit/GameKit.h>
extern NSString *const PresentAuthenticationViewController;
extern NSString *const LocalPlayerIsAuthenticated;

@protocol GameKitHelperDelegate
- (void)matchStarted;
- (void)matchEnded;
- (void)match:(GKMatch *)match didReceiveData:(NSData *)data
fromPlayer:(NSString *)playerID;
@end

@interface GameKitHelper : NSObject<GKMatchmakerViewControllerDelegate, GKMatchDelegate>
@property (nonatomic, readonly) UIViewController *authenticationViewController;
@property (nonatomic, readonly) NSError *lastError;
@property (nonatomic, strong) GKMatch *match;
@property (nonatomic, assign) id <GameKitHelperDelegate> delegate;

+ (instancetype)sharedGameKitHelper;
- (void)authenticateLocalPlayer;
- (void)findMatchWithMinPlayers:(int)minPlayers maxPlayers:(int)maxPlayers
viewController:(UIViewController *)viewController
delegate:(id<GameKitHelperDelegate>)delegate;
@end

GamekitHelper.m

#import "GameKitHelper.h"
NSString *const PresentAuthenticationViewController = @"present_authentication_view_controller";
NSString *const LocalPlayerIsAuthenticated = @"local_player_authenticated";
@implementation GameKitHelper {
BOOL _enableGameCenter;
BOOL _matchStarted;
}

+ (instancetype)sharedGameKitHelper{
static GameKitHelper *sharedGameKitHelper;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
sharedGameKitHelper = [[GameKitHelper alloc] init];
});
return sharedGameKitHelper;
}

- (id)init{
self = [super init];
if (self) {
_enableGameCenter = YES;
}
return self;
}

- (void)authenticateLocalPlayer{
//1
GKLocalPlayer *localPlayer = [GKLocalPlayer localPlayer];
if (localPlayer.isAuthenticated) {[[NSNotificationCenter defaultCenter] postNotificationName:LocalPlayerIsAuthenticated object:nil];
return;
}
//2
localPlayer.authenticateHandler  =
^(UIViewController *viewController, NSError *error) {
//3[self setLastError:error];
if(viewController != nil) {
//4[self setAuthenticationViewController:viewController];
} else if([GKLocalPlayer localPlayer].isAuthenticated) {
//5
_enableGameCenter = YES;[[NSNotificationCenter defaultCenter] postNotificationName:LocalPlayerIsAuthenticated object:nil];
} else {
//6
_enableGameCenter = NO;
}
};
}

- (void)setAuthenticationViewController:(UIViewController *)authenticationViewController{
if (authenticationViewController != nil) {
_authenticationViewController = authenticationViewController;[[NSNotificationCenter defaultCenter] postNotificationName:PresentAuthenticationViewController
object:self];
}
}

- (void)setLastError:(NSError *)error{
_lastError = [error copy];
if (_lastError) {
NSLog(@"GameKitHelper ERROR: %@",[[_lastError userInfo] description]);
}
}

- (void)findMatchWithMinPlayers:(int)minPlayers maxPlayers:(int)maxPlayers
viewController:(UIViewController *)viewController
delegate:(id<GameKitHelperDelegate>)delegate {
if (!_enableGameCenter) return;
_matchStarted = NO;
self.match = nil;
_delegate = delegate;[viewController dismissViewControllerAnimated:NO completion:nil];

GKMatchRequest *request = [[GKMatchRequest alloc] init];
request.minPlayers = minPlayers;
request.maxPlayers = maxPlayers;

GKMatchmakerViewController *mmvc =[[GKMatchmakerViewController alloc] initWithMatchRequest:request];
mmvc.matchmakerDelegate = self;[viewController presentViewController:mmvc animated:YES completion:nil];
}

// The user has cancelled matchmaking
- (void)matchmakerViewControllerWasCancelled:(GKMatchmakerViewController *)viewController {[viewController dismissViewControllerAnimated:YES completion:nil];
}

// Matchmaking has failed with an error
- (void)matchmakerViewController:(GKMatchmakerViewController *)viewController didFailWithError:(NSError *)error {[viewController dismissViewControllerAnimated:YES completion:nil];
NSLog(@"Error finding match: %@", error.localizedDescription);
}

// A peer-to-peer match has been found, the game should start
- (void)matchmakerViewController:(GKMatchmakerViewController *)viewController didFindMatch:(GKMatch *)match {[viewController dismissViewControllerAnimated:YES completion:nil];
self.match = match;
match.delegate = self;
if (!_matchStarted && match.expectedPlayerCount == 0) {
NSLog(@"Ready to start match!");
}
}

#pragma mark GKMatchDelegate
// The match received data sent from the player.
- (void)match:(GKMatch *)match didReceiveData:(NSData *)data fromPlayer:(NSString *)playerID {
if (_match != match) return;
[_delegate match:match didReceiveData:data fromPlayer:playerID];
}

// The player state changed (eg. connected or disconnected)
- (void)match:(GKMatch *)match player:(NSString *)playerID didChangeState:(GKPlayerConnectionState)state {
if (_match != match) return;

switch (state) {
case GKPlayerStateConnected:
// handle a new player connection.
NSLog(@"Player connected!");
if (!_matchStarted && match.expectedPlayerCount == 0) {
NSLog(@"Ready to start match!");
}
break;
case GKPlayerStateDisconnected:
// a player just disconnected.
NSLog(@"Player disconnected!");
_matchStarted = NO;[_delegate matchEnded];
break;
case GKPlayerStateUnknown:
break;
}
}

// The match was unable to connect with the player due to an error.
- (void)match:(GKMatch *)match connectionWithPlayerFailed:(NSString *)playerID withError:(NSError *)error {
if (_match != match) return;

NSLog(@"Failed to connect to player with error: %@", error.localizedDescription);
_matchStarted = NO;[_delegate matchEnded];
}

// The match was unable to be established with any players due to an error.
- (void)match:(GKMatch *)match didFailWithError:(NSError *)error {
if (_match != match) return;

NSLog(@"Match failed with error: %@", error.localizedDescription);
_matchStarted = NO;[_delegate matchEnded];
}
@end

Step 2 : Import GameKit framework & GameKitHelper.h in appDelegate file

Step 3 : Define GKGameCenterControllerDelegate & GKLeaderboardViewControllerDelegate Protocols in appDelegate.h file

Step 4: In didFinishLaunchingWithOptions method write this

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(showAuthenticationViewController) name:PresentAuthenticationViewController object:nil];[[GameKitHelper sharedGameKitHelper] authenticateLocalPlayer];

Game Control Methods

 

- (void)leaderboardViewControllerDidFinish:(GKLeaderboardViewController *)viewController{[[[CCDirector sharedDirector] self] dismissViewControllerAnimated:YES completion:nil];
}

- (void)showAuthenticationViewController
{
GameKitHelper *gameKitHelper =[GameKitHelper sharedGameKitHelper];[[CCDirector sharedDirector] presentViewController:gameKitHelper.authenticationViewController animated:YES completion:nil];
}

Step 5 : Now To Submit Score

-(void)doGameCenterAction:(int)score{
if ([GKLocalPlayer localPlayer].authenticated) {[[GKLocalPlayer localPlayer] loadDefaultLeaderboardIdentifierWithCompletionHandler:^(NSString *leaderboardIdentifier, NSError *error) {
if (error ==nil){
GKScore *myScoreValue = [[GKScore alloc] initWithCategory:@"12345-#####"];
myScoreValue.value = score;[myScoreValue reportScoreWithCompletionHandler:^(NSError *error){
if(error != nil){
NSLog(@"Score Submission Failed");
}else{
NSLog(@"Score Submitted");[[[UIAlertView alloc] initWithTitle:@"Game Center" message:@"Your Score submitted successfully" delegate:self cancelButtonTitle:@"Ok" otherButtonTitles:nil, nil] show];
}
}];
}else{
NSLog(@"Fail");
}
}];
}else{[[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"gamecenter:"]];
}
}

Step 6 : To Show Leaderboard

-(void)doShowLeaderBoard{
if ([GKLocalPlayer localPlayer].authenticated) {[[GKLocalPlayer localPlayer] loadDefaultLeaderboardIdentifierWithCompletionHandler:^(NSString *leaderboardIdentifier, NSError *error) {
if (error ==nil){
GKLeaderboardViewController *lb = [[GKLeaderboardViewController alloc] init];
if(lb != nil){
lb.viewState = GKGameCenterViewControllerStateLeaderboards;
lb.leaderboardDelegate = self;[[CCDirector sharedDirector] presentViewController:lb animated:YES completion:nil];
}
}else{
NSLog(@"Fail");
}
}];
}else{[[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"gamecenter:"]];
}
}

This is all you need to do for implementing Game center, Show Leaderboard & Submit score to the GameCenter.

The most important thing about this tutorial is, it works & provides similar conduct in lower as well as higher iOS versions.

If you are looking to build your iOS8 apps  Contact us  now.

(Visited 10 times, 1 visits today)

Tags: Game Center, Guide for Game Center in iOS 8, how to integrate game center in iphone app, IOS8, Leaderboard, Localization, Tips for Game Center Integration in iOS 8
Share
Share