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:

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://www.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 write me on Twitter. Thanks for reading and happy iCoding!


19 Comments
No, thank YOU very much!
I was thinking on implementing something like this in my game and you just made my work easier.
Thanks, excellent, I’m sure I’ll use it at some point.
Hi! Thanks very much for the tutorial!
I have one question about getting highscrores. How I can get the scrores from the php page to the iphone sdk labels and textboxes e.t.c? I don’t want to use UIWebView.
Please answer to the mail
Very well done ! Love your tuts and I always wonder how to you find time to build them, cz I know how much efforts it takes
For the MySQL,based on my experience I never use FLOAT column type, because I had huge problems with float math on it, I always use DOUBLE instead, which seems to work better.
Also, wouldn’t it be better if the password was sent trough a POST request? Or it was too much code overhead for the simple tutorial ?
Anyhow, I’m always waiting for the new post on your blog, and congrats once more
Marin
@Mikko – You need to make your PHP output XML instead of a table. Then parse this XML in your application into an NSDictionary. From there, you can populate whatever you want with this data.
@Marin – I have never had any issues with FLOAT. But I’m sure you could easily switch it out with DOUBLE. As far as teh POST goes, there are many ways security could be improved. HTTP Basic AUTH would be another way to prevent attacks. I didn’t really want to go too much into it in this tutorial as I wanted to keep things simple and show users how to get a leaderboard up with very little code. Thanks for the suggestion.
Thanks for the code. I was wondering about how to make sure the person can reach the website. It seems that Apple has a framework for checking called SCNetworkReachability and some demo code in the SDK. I’m just adding that here to save people the extra google search.
I cant seem to set up the creat_db.php page I get this error: Could not connect Can’t connect to local MySQL server through socket ‘/tmp/mysql.sock’ (2) and also I am getting confused in xcode. Do you think you could post source code to a sample project that would do everything you described in the tutorial?
Great post. Thanks for this really. I am not a blog reglar blog reader but this blog is truly amazing indeed.
Hi, tnx for this great post. Could you pls place or mail me een .zip with al the files’s?
I build the tutorial but it doesn’t work.
Tnx in advance.
To check for an internet connection, you should use Apple’s Reachability class. Just download it and copy Reachability.h/m to your project. Also, you have to add the SystemConfiguration framework to your project.
https://developer.apple.com/iphone/library/samplecode/Reachability/index.html
Usage:
Reachability* reachability = [Reachability sharedReachability];
[reachability setHostName:@"www.example.com"]; // set your host name here
NetworkStatus remoteHostStatus = [reachability remoteHostStatus];
if(remoteHostStatus == NotReachable) { }
else if (remoteHostStatus == ReachableViaWiFiNetwork) { }
else if (remoteHostStatus == ReachableViaCarrierDataNetwork) { }
Hi, should the submit score method’s return type be NSString *?
Also, if I want to limit the maximum number of entries in the table, how should I modify the code?
Thanks a lot!
I ran into an error when trying to add this to my app:
HighScoresView * hsv = [[HighScoresView alloc] initWithNibName:@”HighScoresView”
bundle:[NSBundle mainBundle]];
[self presentModalViewController:hsv animated:YES];
[hsv release];
The error would say that HighScoresView was undeclared, after a while I got the error to go away. Then I was getting hsv is undeclared and fixed that by adding Controller to the end of each HighScoresView. I was then getting a bad execution error. It seems (I traced through the debugger) that it is not taking the string from my textBox.text (Debugger says it is not a valid CFString. Then when it goes to encode the username it does the same thing and crashes. Do you have any suggestions on how I can fix this? I’ve been puzzle by it for hours now.
-Chris
What if two people enter the same user name? Is there any way to detect if the user name has already been taken? and If so can you explain how one might go about this?
Thanks
Hello,
First I have to say this tutorial has been very helpful, Thanks
I have a few questions though.
I have the leaderboard up and running, and I have it also displaying in my app just fine. A few things that Im running into is when the user clicks the leaderboard button in my app I would like to have them enter there username to submit there high score then have the high scores view controller slides up from the bottom and displays on top of the current view.
Im using your Inserting A UITextField In A UIAlertView, to prompt the user to enter there username. Im not sure how to modify this code, so when the user enters there username and clicks the “OK!” button that it then submits the username and highscore to the leaderbord and closes the UIAlertView and opens the high scores view. And in turn if the user clicks the “Dismiss” button it closes the UIAlertView and opens the high scores view without submitting a score or name.
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@”Enter A Username Here” message:@”this gets covered!” delegate:self cancelButtonTitle:@”Dismiss” otherButtonTitles:@”OK!”, nil];
UITextField *myTextField = [[UITextField alloc] initWithFrame:CGRectMake(12, 45, 260, 25)];
CGAffineTransform myTransform = CGAffineTransformMakeTranslation(0, 60);
[alert setTransform:myTransform];
[myTextField setBackgroundColor:[UIColor whiteColor]];
[alert addSubview:myTextField];
[alert show];
[alert release];
[myTextField release];
The other issue I noticed, is there is nothing stopping someone from submitting multiple high scores, and flooding the leaderboard with just there name and scoe ten times. Is there another “possible simple” PHP script that when submitting a score it does some sort of check, such as checking if the users UDID and username match, and if there score was greater than the one currently on/or in the database then allow them to post it, if not display an alert, or just “Dismiss” the submission and display the high score view.
I know this is asking allot, any help would be great.
Thanks again.
Good Article!
Where is the rest of the tutorial?
I have an online work order system running on MySQL with PHP pages. I want to make an app to retrieve data and post data to the site. I used this tut to create a couple of test pages and can post data and retrieve via Safari. I am a real newbie on iPhone development and could use some help. A tut on posting and retrieving data would be greatly helpful. If there is one somewhere on the web, I can’t find it.
any help on how to identify a user by username/pword instead of udid?
Very Interesting Read! Looking forward to more on this subject Bookmarked this site. Was also curious if anybody could point me to some related material. Thanks in advance.
Great article, I have just got the mysql db up and running and can post from my browser now! Next step to do an iPhone app to test. Thanks again.
PS. you have a spam comment above that slipped in… might wanna delete it
One Trackback
[...] In deze stap schrijft men data naar de database. Meestal wordt deze stap niet beschreven. Er staat hooguit: “…en schrijven gaat precies andersom.” Hier vind je een uitstekend voorbeeld hoe dat wel kan met XML. [...]