In this post, I am proving you only the implementation part for leader board /leaderboard in game center on iPhone.
Copy paste the below code in your .mm file :
- (BOOL)isGameCenterAvailable {
// Check for presence of GKLocalPlayer API.
Class gcClass = (NSClassFromString(@"GKLocalPlayer"));
// The device must be running running iOS 4.1 or later.
NSString *reqSysVer = @"4.1";
NSString *currSysVer = [[UIDevice currentDevice] systemVersion];
BOOL osVersionSupported = ([currSysVer compare:reqSysVer options:NSNumericSearch] != NSOrderedAscending);
return (gcClass && osVersionSupported);
}
- (void)initGameCenter {
// Only continue if Game Center is available on this device
// Authenticate the local player
[self gameCenterAuthenticate];
// Register the GKPlayerAuthenticationDidChangeNotificationName notification
NSNotificationCenter *nc = [NSNotificationCenter defaultCenter];
[nc addObserver: self
selector:@selector(gameCenterAuthenticationChanged)
name:GKPlayerAuthenticationDidChangeNotificationName
object:nil];
}
- (void)gameCenterAuthenticate {
// Authenticate the local user
NSLog(@"Game Center - Trying to authenticate...");
/*if([GKLocalPlayer localPlayer].authenticated == NO) */{
[[GKLocalPlayer localPlayer] authenticateWithCompletionHandler:^(NSError *error) {
if(error == nil) {
NSLog(@"Game Center - Authenticated successfully");
} else {
NSLog(@"Game Center - Failed to authenticate");
}
}];
}
}
- (void)gameCenterAuthenticationChanged {
[self gameCenterAuthenticate];
}
- (void) registerForAuthenticationNotification
{
NSNotificationCenter *nc = [NSNotificationCenter defaultCenter];
[nc addObserver: self
selector:@selector(authenticationChanged)
name:GKPlayerAuthenticationDidChangeNotificationName
object:nil];
}
- (void)submitHighScore {
// Report the high score to Game Center
GKScore *scoreReporter = [[[GKScore alloc] initWithCategory:@"HIGHEST_SCORES"] autorelease];
scoreReporter.value = finalScore;
[scoreReporter reportScoreWithCompletionHandler:^(NSError *error) {
if (error == nil) {
NSLog(@"Game Center - High score successfully sent");
}
}];
// Show the Game Center leaderboard
[self viewLeaderboard];
}
- (void)viewLeaderboard {
// Show the leaderboard
[self showLeaderboardCategory:@"HIGHEST_SCORES"];
}
- (void)showLeaderboardCategory:(NSString *)category {
// Show leaderboard
GKLeaderboardViewController *leaderboardController = [[GKLeaderboardViewController alloc] init];
if (leaderboardController != nil) {
leaderboardController.category = category;
leaderboardController.leaderboardDelegate = self;
// Add the leaderboard view to the EAGLView
[self presentModalViewController:leaderboardController animated: YES];
}
[self retrieveFriends];
}
- (void)retrieveFriends
{
GKLocalPlayer *lp = [GKLocalPlayer localPlayer];
if (lp.authenticated)
{
[lp loadFriendsWithCompletionHandler:^(NSArray *friends, NSError *error) {
if (error == nil)
{
// use the player identifiers to create player objects.
}
else
{
// report an error to the user.
}
}];
}
}
- (void) loadPlayerData: (NSArray *) identifiers
{
[GKPlayer loadPlayersForIdentifiers:identifiers withCompletionHandler:^(NSArray *players, NSError *error) {
if (error != nil)
{
// Handle the error.
}
if (players != nil)
{
// Process the array of GKPlayer objects.
}
}];
}
- (void)leaderboardViewControllerDidFinish:(GKLeaderboardViewController *)viewController {
// Remove the leaderboard view from the EAGLView
[self dismissModalViewControllerAnimated:YES];
[viewController release];
}
- (void) retrieveTopTenScores
{
GKLeaderboard *leaderboardRequest = [[GKLeaderboard alloc] init];
if (leaderboardRequest != nil)
{
leaderboardRequest.playerScope = GKLeaderboardPlayerScopeGlobal;
leaderboardRequest.timeScope = GKLeaderboardTimeScopeAllTime;
leaderboardRequest.range = NSMakeRange(1,10);
[leaderboardRequest loadScoresWithCompletionHandler: ^(NSArray *scores, NSError *error) {
if (error != nil)
{
// handle the error.
}
if (scores != nil)
{
// process the score information.
}
}];
}
}
in your .h file, please add the following things:
Declare the below methods:
- (BOOL)isGameCenterAvailable;
- (void)initGameCenter;
- (void)gameCenterAuthenticate;
- (void)gameCenterAuthenticationChanged;
- (void)submitHighScore;
- (void)viewLeaderboard;
- (void) retrieveFriends;
- (void) loadCategoryTitles;
- (void) registerForAuthenticationNotification;
- (void) reportScore: (int64_t) score forCategory: (NSString*) category;
- (void)leaderboardViewControllerDidFinish:(GKLeaderboardViewController *)viewController;
Also add, GKLeaderboardViewControllerDelegate in your class declaration.
Ex.
@interface GameOverViewController : UIViewController <UITextFieldDelegate, GKLeaderboardViewControllerDelegate >
Here is the hierarchy of calling these functions:
if([self isGameCenterAvailable])
{
[self initGameCenter];
[self gameCenterAuthenticate];
[self submitHighScore];
[self retrieveTopTenScores];
[self retrieveFriends];
}
Include the header files, #import <GameKit/GameKit.h>.
And add gamekit in the frameworks.
Here is the description for the above code:
Before you send your score to the game center, you need to follow the below steps:
1) Check weather the device supports game center or not [ isGameCenterAvailable ]
2) Check weather the current player has logged in or not.. i.e is this guy has registered with game center or not.
3) Then submit your score.
4) Then view the leader board :)
w.r.t the method, submitHighScore , I have used a variable called finalScore where I have my score which need to send to the game center.
So,you use your own variable to send the score or you can also hardcode it for testing purpose.
HIGHEST_SCORES is the one I registered the high score level in iTunesConnect.
So, make sure you already configured your game in the iTunesConnect before you actually start implementing game center. If you don't configure it, it won't work.
If you have any more doubts, please let me know.
Happy coding :)
Pradeep Daram.
pradeepfriend2000@gmail.com.
Nice post dude.....
ReplyDeletewhat if we want to implement custom leaderboard with our own graphics...?
I never tried yaar. Sorry, I can't help you out in this regard :(
ReplyDeletehmmm.... k yaar ... i need to implement that in a week bro... watt lagi huyi hai yaar.....
ReplyDeleteVery good Bro...
ReplyDeletewhat if I want to share this leader board on face book ?
hi ..
ReplyDeletefrom where i can download gamekit ?? api