IOS-Integrated Game Center (leader board)

Source: Internet
Author: User

Leader board was recently used in Game center. In fact, this thing is very simple, just easy to forget. So I'm going to write it down.


Create an app on ITunes Connect, and then enable Game Center

The creation of the app is omitted, and once created, no commits are required. We can set up Game center.

First click on the new app to find the game Center,



You can add some items by clicking into the specific Game center settings. is very simple, basically have a hint, need to pay attention to is the leaderboard ID, have to make a separate, do not repeat. This ID needs to be used in the code.

With just a few simple steps, Game Center is enabled.



Introducing Game Center in your code

Open Game Center in Xcode's project,




Directly open on the line, feel iOS development more and more fools, hehe.

The next step is to implement the specific code.


Code implementation

First, add the following code to the right place: usually

-(BOOL) Application: (uiapplication *) application didfinishlaunchingwithoptions: ( Nsdictionary *) launchoptions

Double ver = [[Uidevice currentdevice].systemversion doublevalue];    if (Ver < 6.0) {        [[Gklocalplayer Localplayer] authenticatewithcompletionhandler:^ (nserror *error) {                    }];    }    Else    {[        [Gklocalplayer Localplayer] Setauthenticatehandler: (^ (uiviewcontroller* viewcontroller, NSError *error) {                    })];    }        nsnotificationcenter* ns = [nsnotificationcenter defaultcenter];        [NS addobserver:self selector: @selector (authenticationchanged) Name: Gkplayerauthenticationdidchangenotificationname Object:nil];    
We have added an observer to Game center, so we need to provide a function in self. This is a callback function, if the user does not log in to Game Center, then will run to the bottom, if the landing will run to the top.
-(void) authenticationchanged{    if ([Gklocalplayer localplayer].isauthenticated) {        NSLog (@ " Authenticationchanged, authenticated ");                            }    else    {                NSLog (@ "authenticationchanged, not Authenticated");}    }

The next step is to submit and display leader board. The details of Apple's official website are clear. I found here on the Internet a package of source code, I slightly modified a bit. The specific code to see the last side (attached). Here is the main introduction to the use process. Add a property first.

@property (ReadWrite, retain) Playermodel * player;
Add one more function, such as:

-(void) updateplayer{        if (!self.player | |![ Self.player.currentPlayerID Isequaltostring:[gklocalplayer Localplayer].playerid]) {                [Self.player release];                Self.player = [[Playermodel alloc] init];    }    [[self player] loadstoredscores];}
This function will be transferred to the authenticationchanged inside.

-(void) authenticationchanged{    if ([Gklocalplayer localplayer].isauthenticated) {        NSLog (@ " Authenticationchanged, authenticated ");                [Self updateplayer];    }    else    {        NSLog (@ "authenticationchanged, not Authenticated");}    }
Updateplayer This function is more critical.

It supports multi-user, if it is the first time to log in to Game Center, then create an object, if it is a user login, then put the previous release, and then create a new object. Then call Loadstoredscore.

The Loadstoredscore will read the points that need to be transferred from the local file and pass it to the Game Center server.

The above code means that when the app is up, authenticationchanged is called, and if it's logged in, a Playermodel object is created. If there is data that needs to be uploaded, read it and try uploading it.

In fact, this is a protective measure, and we'll talk about why we need to do it later.


The next step is to see if the data is instantly uploaded in the game.

First, add a function that sends data to the server. Self.player Submitscore, this function will be seen later. With this function, we can call to send data to the server somewhere in the game or application. The value of Leaderboard_distance is the leaderboard ID created in connect above.

-(void) Storescore: (NSNumber *) distance{    if (!self.player)        return;        int64_t score64 =  [distance longlongvalue];    Gkscore * Submitscore = [[Gkscore alloc] initwithcategory:leaderboard_distance];    [Submitscore setvalue:score64];    [Self.player Submitscore:submitscore];    [Submitscore release];}

OK, that's easy. Let's talk about the principle of playermodel. Because we often fail to submit because of network reasons, especially in China. Therefore, the playermodel inside a mechanism, if the submission fails, the data to be submitted to the local file, at the appropriate time to try to commit.

-(void) Submitscore: (Gkscore *) score {    if ([Gklocalplayer localplayer].authenticated) {        if (!score.value) {            //Unable to validate data.             return;        }                Store the scores if there is an error.         [Score reportscorewithcompletionhandler:^ (Nserror *error) {            if (!error | | (! [ERROR code] &&! [Error domain]) {                //score submitted correctly. Resubmit others                [self resubmitstoredscores],            } else {                //Store score for next authentication.                 [Self storescore:score];            }        }];    } }
The main meaning of this function is to try to commit the data first, and if it succeeds, simply commit the other data (it may fail before the submission). If it fails, then save the data [self storescore:score], save to an array, and write to the local file. This gives you the opportunity to submit it again elsewhere. Complete code look behind.

Now see if leader board is displayed in the app. Look at the following code Gamecenterauthenticationcomplete is a bool that I use internally to mark whether the user is logged in to Game Center. Call this code and the Game Center of iOS will be displayed.

-(void) showgamecenter{    if (gamecenterauthenticationcomplete) {        Gkleaderboardviewcontroller * Leaderboardviewcontroller = [[Gkleaderboardviewcontroller alloc] init];        [Leaderboardviewcontroller setcategory:leaderboard_distance];        [Leaderboardviewcontroller Setleaderboarddelegate:_viewcontroller];        [Self.viewcontroller Presentmodalviewcontroller:leaderboardviewcontroller  Animated:yes];        [Leaderboardviewcontroller release];}    }


Attached, complete Playermodle code:

Header file:

#import <Foundation/Foundation.h> #import <GameKit/GameKit.h> @interface playermodel:nsobject {Nslock * Writelock;} @property (readonly, nonatomic) nsstring* Currentplayerid; @property (readonly, nonatomic) NSString * Storedscoresfilename; @property (readonly, nonatomic) Nsmutablearray * storedscores;//Store score for submission at a late R time.-(void) Storescore: (Gkscore *) score;//Submit stored scores and remove from stored scores array.-(void) resubmitst oredscores;//Save store on disk. -(void) writestoredscore;//Load stored scores from disk.-(void) loadstoredscores;//Try to submit score, store on failure .-(void) Submitscore: (Gkscore *) score; @end


M File:

#import "PlayerModel.h" @implementation playermodel@synthesize storedscores, Currentplayerid, storeds    coresfilename;-(id) init{self = [super init];        if (self) {currentplayerid = [[NSString stringwithformat:@ "%@", [Gklocalplayer Localplayer].playerid] retain];        nsstring* Path = [Nssearchpathfordirectoriesindomains (nsdocumentdirectory, Nsuserdomainmask, YES) objectAtIndex:0];        Storedscoresfilename = [[NSString alloc] initwithformat:@ "%@/%@.storedscores.plist", Path, Currentplayerid];    Writelock = [[Nslock alloc] init]; } return self;}    -(void) dealloc{[storedscores release];    [Writelock release];    [Storedscoresfilename release];        [Currentplayerid release]; [Super Dealloc];}  Attempt to resubmit the scores.-(void) resubmitstoredscores{if (storedscores) {//keeping an index prevents        New entries to being added when the network is down int index = (int) [Storedscores count]-1; while (Index >= 0) {Gkscore * score = [Storedscores Objectatindex:index];            [Self submitscore:score];            [Storedscores Removeobjectatindex:index];        index--;    } [self writestoredscore]; }}//Load stored scores from disk.-(void) loadstoredscores{Nsarray * unarchivedobj = [Nskeyedunarchiver unarchiveobje        Ctwithfile:storedscoresfilename];        if (unarchivedobj) {storedscores = [[Nsmutablearray alloc] initwitharray:unarchivedobj];    [Self resubmitstoredscores];    } else {storedscores = [[Nsmutablearray alloc] init]; }}//Save stored scores to file.    -(void) writestoredscore{[Writelock Lock];    NSData * Archivedscore = [Nskeyedarchiver archiveddatawithrootobject:storedscores];    Nserror * ERROR;    [Archivedscore writetofile:storedscoresfilename Options:nsdatawritingfileprotectionnone error:&error]; if (error) {//Error saving file, handle accordingly} [Writelock unlock];} Store score forSubmission at a later time.-(void) Storescore: (Gkscore *) score {[Storedscores addobject:score]; [Self writestoredscore];} Attempt to submit a score. On the error store it for a later time.-(void) Submitscore: (Gkscore *) score {if ([Gklocalplayer Localplayer].authentica             Ted) {if (!score.value) {//Unable to validate data.        Return         }//Store the scores if there is an error. [Score reportscorewithcompletionhandler:^ (Nserror *error) {if (!error | | (! [ERROR code] &&! [Error domain]) {//score submitted correctly.            Resubmit others [self resubmitstoredscores];                 } else {//Store score for next authentication.            [Self storescore:score];    }        }]; }} @end













IOS-Integrated Game Center (leader board)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.