iPhone Coding Tutorial – Creating an Online Leaderboard For Your Games

    October 29th, 2009 Posted by: - posted under:Tutorials

    Submitting High Scores To The Leaderboard

    Submitting the high scores is very simple. I have created a method that you can drop right in your code and use to submit the scores to your server. Here is the code for this method.

    - (void) submitScore:(float) theScore username:(NSString *) username {
     
            NSString * udid = [[UIDevice currentDevice] uniqueIdentifier];
            NSString * secret = @"some_secret";
            username = [username stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
     
            NSString *urlString = [NSString stringWithFormat:@"http://icodeblog.com/ws/put_score.php?secret=%@&udid=%@&name=%@&score=%f",
                                                       secret,udid,username,theScore];
            NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:urlString]];
            NSError * e;
            NSData          *data = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:&e];
            return [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
    }

    Let’s go over this code. The first bit of code initializes some of the variables that will be sent to the server. We get the user’s UDID and the secret for accessing our server. Also, we must encode the username to be passed to our server in case the user enters any special characters.

    Following that, we build the URL that we will be making our request to and build an NSURLRequest from that. Make sure you replace icodeblog with the URL of your server. Now the magic…

    We call the sendSynchronousRequest method of NSURLConnection to send the data to our server. Using Synchronous instead of Asynchronous tells the calling thread to block and wait for the request to complete before returning. I went this route in the sample code just to simply things. You could have also sent the data Asynchronously, but you would then have to implement all of the delegate methods. I will leave that up to you as a challenge.

    Once the data returns from the request, we simply convert it to an NSString and return it. Here is a quick example of how you would call this method.

    [self submitScore:score username:usernameTextbox.text];

    This code assumes that you prompted the user for their username via some sort of text box name usernameTextbox. You can choose to implement this however you like.

    The last part of this tutorial will show you a simple way to display the leaderboard in a UIWebview within your application.

    Displaying the leaderboard In Your Application

    This section of the tutorial will show you how to display the leaderboard data in a UIWebView within your application. One assumption I am going to make is that you will be displaying the leaderboard from inside a view controller.

    Here are the steps involved in displaying the leaderboard data.

    1. Add a new view controller to your project and name it HighScoresViewController. Make sure you check to have it create the .h and .xib interface file.

    2. We need to write the code to display this view controller. Go to the method where you want to display the high scores table. This could be in response to a button click or done automatically at the end of the game. Some simple code for doing this is:

    HighScoresView * hsv = [[HighScoresView alloc] initWithNibName:@"HighScoresView"
            bundle:[NSBundle mainBundle]];
    [self presentModalViewController:hsv animated:YES];
    [hsv release];

    This will cause the high scores view controller to slide up from the bottom and display on top of the current view.

    3. Now open up HighScoresViewController.h. Add a declaration for an IBOutlet UIWebview in the header file as well as an IBAction named done. Done will get called when the user presses a done button to hide the high scores table. Your header file should now look something like this.

    @interface HighScoresViewController : UIViewController {
            IBOutlet UIWebView * webview;
    }
     
    @property(nonatomic, retain) UIWebView *webview;
    -(IBAction) done:(id) sender;
     
    @end

    4. Open up Interface Builder and add a Toolbar with a button that says “Done” and a UIWebView. The interface should look like this:
    screenshot_01

    5. Connect the UIWebView to your webview outlet and connect the touchUpInside method of the done button to your done IBAction and close Interface Builder.

    6. Implement the viewDidLoad method of the HighScoresViewController to load your high scores webpage into the webview. Here is some code for doing this:

    - (void)viewDidLoad {
            [super viewDidLoad];
            NSString *address = @"http://icodeblog.com/ws/get_scores.php";
            NSURL *url = [NSURL URLWithString:address];
            NSURLRequest *requestObj = [NSURLRequest requestWithURL:url];
            [self.webview loadRequest:requestObj];
    }

    One thing to note here is I am calling get_scores.php without any parameters. If you wanted to change the data displayed (or paginate) you might add something like ?type=name&name=brandontreb to show scores for a specific user. You really have a lot of freedom here to design this how you want.

    5. Implement the done method. Since we displayed this view controller using presentModalViewControler, we can simply do the opposite by calling dismissModalViewController on the parent view controller. Here is the code for the done method.

    -(IBAction) done:(id) sender {
            [self.parentViewController dismissModalViewControllerAnimated:YES];
    }

    And that’s it! You now have a fully featured leaderboard that you can use in all of your iPhone games.
    If you have any questions, feel free to leave them in the comments section of this post or . Thanks for reading and happy iCoding!

    Pages: 1 2 3 4