iOS LeaderBoard

A leaderboard is an organized list of the best scores submitted by players of your game. When a user submits a better score than his last submitted score, the better score will be displayed on the existing score board and the existing score will be removed/ ignored from the board. Additionally users could also check social rankings by connecting to social accounts.

Introduction to the App42 Backened and the Leaderboard Service

App42 BaaS (Backend as a Service) helps developers reduce their time, effort and cost of application development by providing a ready made scalable, secure and robust backend. App42 works by providing native SDKs in different languages (for different platforms) and provides ready-made services such as User Management, Social Leaderboard, Avatar Management etc. in addition to core services such as NoSQL Storage, File Storage, Logging etc.

Leaderboard Service Introduction

Scoreboard Management allows game developers to create a game and then maintain its scoring data on the cloud using simple high level APIs to save and retrieve scores. You can create different leaderboards within the same application by creating different ‘game’ instances (say for storing data for different levels or modes in the application).

One can query for average or highest score for a user in a Game. It also records and provides global rankings of users across the game as well as social leaderboards i.e. a list of top N rankers from the user’s facebook friends. You can customize the leaderboards easily to achieve weekly, daily leaderboards or leaderboards based on any other meta data.

What are we going to do

We will use an existing game (in this case Sprite Kit iOS 7) to explain App42 leaderboard integration. It will require users to sign-in from Facebook to submit scores and to view the leaderboards. Display a list of top N scorers in the game using App42 backend service. Display a list of top N scorers in the game among the user’s Facebook friends (social-leaderboard) using App42 backend service.

Sample Prerequisites

Download the source code of the game with the leaderboard integration Link.

App42 Setup

As you are integrating App42 backend services, you have to get your application keys from the ShepHertz developer dashboard - AppHq. These keys identify your application on the App42 backend. An App42 application is a sandbox environment for your application on our cloud.

Follow the simple steps by signing up (free) and getting your application keys mentioned at Link

Now we need to configure the files of the sample with your keys. To do that open LDConstants.h class available in the sample project and add the API Key and Secret Key.

APP42_APP_KEY         @"Your Application App Key"
APP42_SECRET_KEY      @"Your Application Secret Key"

App42 backend provides many ready made modules (storage, reward management, push, scoreboards etc.). In this example, since we are using leaderboards, we will need to create a ‘game’ in our app. App42 backend scoreboard services allow you to build multiple leaderboards inside the same App for different ‘games’. For example - if you want to have different leaderboards for different levels (or modes) in your application, you will need to create different ‘games’.

To create a game in Shephertz AppHQ Console, do the following : -

  • Go to AppHQ page.
  • Select Business Service Manager in AppHQ Menu.
  • Select Game section.
  • Add new Game.

Now, update the game name to GAME_NAME in LDConstants.h class.

GAME_NAME              @"Your Game Name"

The last step is to specify a database name. This is required for the social integration as it will be used to contain the metadata associated with scores (eg: users display name). Internally, this will rely on our NoSQL storage service and is useful in customizing the leaderboards. This can be extended to add more relevant data such as location, age etc. if you want. In this case we will use it store the Facebook display name corresponding the scores being submitted.

#define DB_NAME               @"ScoreDB"
#define COLLECTION_NAME       @"ScoreCollection"

Your application can have multiple collections (distinguished based on collection name) but a single DB. In this case we just need a single collection.

Facebook Setup

In case you are integrating basic leader board you do not require anything more, however to integrate social leaderboard you have to register the App at Developer Facebook dashboard first. Facebook is only required to get your social ranking. On successful registration follow the shown steps to setup Facebook App ID and URL scheme details. For more details about Facebook integration follow Link.

FB

Now, we are done with all the prerequisites and can go ahead and run the sample.

Follow steps shown below: * This would be your landing screen. Tap on Play and Start playing the game.

play

  • The objective of the game is to protect your space craft from the red colored missile. As long as you can survive you will score more… Move your space craft up and down by tapping in the respective direction. You will be rewarded with 50 points for each missile that disappears from screen.

Game Play

  • Once missile collides with your space craft your game is over. You can play again or submit score.

Game Over

  • On tapping on submit score it will ask you to login first with your Facebook account. The saveScore API requires you to provide the username for the score. Its important that this is unique as it will be used to distinguish the user’s score from others. In this game we are saving Score using the user’s unique Facebook Id (and NOT the display name which can be the same as other users).

FaceBook

  • On successful submission of the score you could tap on the leaderboard button and can easily toggle between Global and Social leader board. The social leaderboard is the leaderboard that lists top Rankers among the user’s facebook friends.

LeaderBoard

How does the integration works

First you need to initialize the App42API singleton with your application keys

[App42API initializeWithAPIKey:APP_KEY andSecretKey:SECRET_KEY];
[App42API setDbName:DB_NAME];

Building the ScoreBoardService

App42 API provides various ready made modules (services). To use them you need to build the corresponding service objects. In this case we have to initialize App42 ScoreBoardService object.

ScoreBoardService *scoreboardService = [App42API buildScoreBoardService];

Saving user score

For this you need to use the saveUserScore API.

Submit Score View

Facebook login View

-(BOOL)saveScore {
    BOOL _success = false;
    @try {
        NSString *name = [[PWFacebookHelper sharedInstance] userName];
        ScoreBoardService *scoreboardService = [App42API buildScoreBoardService];
        NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:_userID,@"UserID",[NSNumber numberWithInt:_score],@"Score",name,@"Name", nil];
        [scoreboardService addCustomScore:dict collectionName:COLLECTION_NAME];

        Game *game=[scoreboardService saveUserScore:GAME_NAME gameUserName:_userID gameScore:_score];
        if(game.isResponseSuccess) {
            NSLog(@"saveScore Success");
            _success = true;
        }
    }
    @catch (App42Exception *exception) {
        NSLog(@"%@",[exception description]);
    }
    return _success;
}

Getting top rank list:

To get the global leaderboard you need to simply use getTopNRankers API. However, for social leaderboard, a few more lines of code are required. Once your Facebook auth is done, we need to set user credential to the scoreBoardService object. This is so that the backend can determine who the user’s friends are and then build a customized leaderbaord list for you in return. Once set, you simply need to call getTopNRankersFromFacebook API(requires your Facebook access token).

Leader Board Home View

Here we are fetching Top Rank List:

-(NSMutableArray*)getScores {
    if (!_app42Intialized) {
        [App42API initializeWithAPIKey:APP42_APP_KEY andSecretKey:APP42_SECRET_KEY];
        [App42API setDbName:DB_NAME];
        _app42Intialized = true;
    }

    ScoreBoardService *scoreboardService = [App42API buildScoreBoardService];
    [scoreboardService setQuery:COLLECTION_NAME metaInfoQuery:Nil];

    Game *game=[scoreboardService getTopNRankers:GAME_NAME max:MAX_NUMBER_OF_RECORDS_DISPLAYED_IN_LB];
    NSMutableArray *scoreList = game.scoreList;
    return scoreList;
}

And Here we are fetching Top Facebook Friend Ranks list.

-(NSMutableArray *) getFBFriendScores {
    if (!_app42Intialized) {
        [App42API initializeWithAPIKey:APP42_APP_KEY andSecretKey:APP42_SECRET_KEY];
        [App42API setDbName:DB_NAME];
        _app42Intialized = true;
    }

    ScoreBoardService *scoreboardService = [App42API buildScoreBoardService];
    [scoreboardService setQuery:COLLECTION_NAME metaInfoQuery:Nil];
    
    NSString *accessToken = [[[[PWFacebookHelper sharedInstance] loggedInSession] accessTokenData] accessToken];
    Game *game=[scoreboardService getTopNRankersFromFacebook:GAME_NAME fbAccessToken:accessToken max:MAX_NUMBER_OF_RECORDS_DISPLAYED_IN_LB];
    NSMutableArray *scoreList = game.scoreList;
    return scoreList;
}

LeaderBoard View

How to integrate leaderboard services to the existing game

Now that we know how the sample works, lets see the steps required to integrate this with your own game.

You have to drag and drop following folders from the sample project to your existing project.

  1. App42Helper

  2. LeaderBoard

Project Navigator Folders

Now, You can customize the LDLeaderBoard_iPad & LDLeaderBoard_iPhone based on your design and requirement. The rest of the steps are the same as explained in the Prerequisites.

Summary

In this article we saw how to integrate App42 backend score board services. Also we saw how users can save scores to the App42 backend and get back a Leaderboard against global and facebook friends. The integration concepts are independent of the game engine and can be applied for any application.

Copyright © 2017 ShepHertz Technologies Pvt Ltd. All rights reserved.   | Terms & Conditions | Privacy Policy