Today I'm going to show you guys how to create a very simple high score system.
1. Make a new project. We're gonna use a View-based Application. Name it "PHP Scores".
2. Open up your view controller XIB file. Follow my video tutorial.
3. Go to Classes > PHP_ScoresViewController.h and add the following to your @interface statement.
Add below @implementation:
Code:
@synthesize countTimer, winAlert, loseAlert;
Code:
UIAlertView *winAlert;
UIAlertView *loseAlert;
NSTimer *countTimer;
NSUInteger time;
4. Click
here to download the 4 PHP files that we will use to show the high scores. The files work on Apache, but depends on what web server you have.
5. Now extract the zip file and open up index.php. At the top of the file, you'll see:
HTML Code:
<title>"Game Name Here" Scores</title>
Replace "Game Name Here" with the name of your game. Now save your file.
6. Open up "post.php", and follow step 5 again, except with post.php instead of index.php.
7. Now you need to get a website host that has Apache on it. Hostmonster is paid, but works really well. I can't provide links to free sites right now.
8. Now make a directory named "scores" on your website wherever you want. this will host our PHP files.
9. Upload index.php, bar.png, posts.txt, post.php, and submit.php to the scores directory. We're now done with The PHP side.
Now we're moving on to the applications end. For this game, I have to clear all 5 boxes in less than 5 seconds.
10. Go to Classes > PHP_ScoresViewController.m. In the IBAction, pushButton1, enter the following code.
Code:
- (IBAction)push1 {
button1.hidden = YES;
if (button1.hidden == YES) {
if (button2.hidden == YES) {
if (button3.hidden == YES) {
if (button4.hidden == YES) {
if (button5.hidden == YES) {
[countTimer invalidate];
}
}
}
}
}
}
11. Now, Copy that code into the other IBAction's besides pushStart. Now change the top line to button#.hidden = YES. Then we stop the timer so it stops the time so we can freeze it to read the score.
# = Then button number we called it in Interface Builder.
12. Now we need To tell it if all buttons are hidden, pop up the alert view we declared in the .h to pop up with the different selections the user can perform. Indside the bottom "if" statement, copy this alert view code into each bottom if statement in each action.
Code:
winAlert = [[UIAlertView alloc] initWithTitle:@"You've won!" message:@"This gets covered." delegate:self cancelButtonTitle:@"Dismiss" otherButtonTitles:@"Submit", @"High Scores", nil];
[winAlert show];
[winAlert release];
ABOVE: Setting up the alert when you win.
13. Lets start the code to start the game. Lets go to our "pushStart" action and type the following code.
Code:
time = 5.0;
countTimer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(countDown) userInfo:nil repeats:YES];
ABOVE: We're saying that time will equal 5 seconds when we hit start. That is setting the time that you have in the beginning. We then start a timer to our countDown statement we will add in the next step.
14. Now, we're going to tell time to countdown when we hit start. It will countdown since we added the NSTimer to "pushStart". Type the following code below the IBAction "pushStart".
Code:
- (void)countDown {
time = time -1;
[self updateLabel];
if (time == 0) {
time = time +0;
[self updateLabel2];
}
}
ABOVE: Telling time that time will equal time -1 stating that time will go down 1 second. We then tell it to start the updateLabel statement we will create in the next step. Next, we say that if time is 0, basically game over, to not count anymore, by adding zero.
15. Lets add the updateLabel statement. This will update the label to whatever time is. Type the following code below the countDown statement.
Code:
-(void)updateLabel {
timeLabel.text = [NSString stringWithFormat:@"%i", time];
}
ABOVE: Setting the labels text to whatever time is by using %i to show time in the label.
16. Next, lets make our updateLabel2 statement. Copy the following code below the updateLabel statement.
Code:
-(void)updateLabel2 {
countLabel.text = [NSString stringWithFormat:@"5", time];
[countTimer invalidate];
}
ABOVE: Resetting the labels text to 5, but still hastime going invisibly since we added 0. Next we invalidate the timer which stops the counting.
17. Now go back to our countDown statement and in the "if time == 0" statement, add the following.
Code:
if (button1.hidden == NO) {
loseAlert = [[UIAlertView alloc] initWithTitle:@"You've lost!" message:@"Better luck next time." delegate:self cancelButtonTitle:@"Dismiss" otherButtonTitles:nil];
[loseAlert show];
[loseAlert release];
}
if (button2.hidden == NO) {
loseAlert = [[UIAlertView alloc] initWithTitle:@"You've lost!" message:@"Better luck next time." delegate:self cancelButtonTitle:@"Dismiss" otherButtonTitles:nil];
[loseAlert show];
[loseAlert release];
}
if (button3.hidden == NO) {
loseAlert = [[UIAlertView alloc] initWithTitle:@"You've lost!" message:@"Better luck next time." delegate:self cancelButtonTitle:@"Dismiss" otherButtonTitles:nil];
[loseAlert show];
[loseAlert release];
}
if (button4.hidden == NO) {
loseAlert = [[UIAlertView alloc] initWithTitle:@"You've lost!" message:@"Better luck next time." delegate:self cancelButtonTitle:@"Dismiss" otherButtonTitles:nil];
[loseAlert show];
[loseAlert release];
}
if (button5.hidden == NO) {
loseAlert = [[UIAlertView alloc] initWithTitle:@"You've lost!" message:@"Better luck next time." delegate:self cancelButtonTitle:@"Dismiss" otherButtonTitles:nil];
[loseAlert show];
[loseAlert release];
}
ABOVE: Saying that if any one of the buttons aren't hidden, pop up the you lost alert view.
18. Go to Classes > PHP_ScoresViewController.h and add the following to our @interface.
Code:
UITextField *userName; //This goes in @interface
@property (nonatomic, retain) UITextField *userName; // Below bottom @property method
19. We are now going to add a text field to our win alert. This is where we will enter our username to send to our site. Type the following code in each of our winAlert statements above [winAlert show];
Code:
userName = [[UITextField alloc] initWithFrame:CGRectMake(12.0, 45.0, 260.0, 25.0)];
[userName setBackgroundColor:[UIColor whiteColor]];
[userName setBorderStyle:UITextBorderStyleRoundedRect];
userName.backgroundColor = [UIColor clearColor];
userName.returnKeyType = UIReturnKeyDone;
userName.keyboardAppearance = UIKeyboardAppearanceAlert;
[userName addTarget:self action:@selector(userNameReturnKey) forControlEvents:UIControlEventEditingDidEndOnExit];
[userName resignFirstResponder];
[winAlert addSubview:userName];
20. Now add the following code to detect which button in the alert view is pressed and its action. Paste this below updateLabel2.
Code:
- (void)alertView:(UIAlertView *)winAlert clickedButtonAtIndex:(NSInteger)buttonIndex {
if (buttonIndex == 1) {
}
if (buttonIndex == 2) {
}
}
ABOVE: Adding our NSInteger, buttonIndex, to detect which button is pressed and its action.
buttonIndex 1 = Submit
buttonIndex 2 = High Scores
21. Connect to submit.php to send the score. Well, here we go! Type the following in the buttonIndex 1 statement.
Code:
NSString *score = [[NSString alloc] initWithFormat:[countLabel text]];
NSString *user = [[NSString alloc] initWithFormat:[userName text]];
NSString *urlToAuthPage = [[NSString alloc] initWithFormat:@"&username=%@&score=%@", user, score];
NSLog(urlToAuthPage);
NSData *postData = [urlToAuthPage dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:NO];
NSString *postLength = [NSString stringWithFormat:@"%d",[urlToAuthPage length]];
NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
[request setURL:[NSURL URLWithString:[NSString stringWithFormat:@"http://yourdomain.com/scores/submit.php"]]];
[request setHTTPMethod:@"POST"];
[request setValue:postLength forHTTPHeaderField:@"Content-Length"];
[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
[request setHTTPBody:postData];
NSURLConnection *conn = [[NSURLConnection alloc]initWithRequest:request delegate:self];
if (conn) {
NSLog(@"Connection Successful");
}
else {
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Error Connection" message:@"There was an error connecting" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
[alert show];
[alert release];
}
ABOVE: We convert our text field and label to an NSString. Now we create an NSLog that is put together well to be read in the Console to make sure the right outlet is being read. We then make our NSStrings ASCII Encoding language. We then create a URL request a connection to our PHP script on our server. Next, we locate the URL of our PHP script that submits the score, submit.php then tell it that its a form. We then make a connect to request that allows us to get into the script. Then an NSLog and alert view to say if there is an error or success.
22. Now follow
this tutorial on switching views. We will switch to a view that holds a web view showing our scores. Use buttonIndex 2 statement.
23. In that tutorial add a web view to it and follow my tutorial
here to load a page. The page is "http://yourdomain.com/scores/index.php".
Now you now have global scores for your app. Questions? Email me
here.