Mar 27 2010

Iphone Programming Part 2 – Intro to Views

Welcome to iphone programming part 2, introduction to views. In this tutorial I’ll go over creating an application from scratch that transitions between 2 different views using the iphone’s built in UINavigationController and the navigation stack. If you haven’t done so already, I suggest reading through my first iphone article. If you already have a basic understanding of how to create an iphone application and hooking up IBOulets and IBActions in interface builder then you can head straight into this article. So let’s jump into it, and as always if you have any questions feel free to leave a comment and I’ll get back to you.

Let’s start out by opening up XCode and creating a new window based application from the standard iphone OS templates. Save the file to wherever you save your iphone files to and create.

Once you create and save your new window-based application, open up the classes and resources folders in the XCode folder explorer. Open up the ViewDemoAppDelegate.h and insert the following code…

//
//  ViewDemoAppDelegate.h
//  ViewDemo
//
//  Created by Mark Hazlett on 10-03-26.
//  Copyright Code Perspective 2010. All rights reserved.
//
 
#import <UIKit/UIKit.h>
@interface ViewDemoAppDelegate : NSObject
{
    UIWindow *window;
    UINavigationController *navController;
}
 
@property (nonatomic, retain) IBOutlet UIWindow *window;
 
@end

All we’re doing here is creating a UINavigationController object so that we can access it in our application delegate implementation file. Let’s go ahead and open up our ViewDemoAppDelegate.m and add the following code to the application did finish launching method.

- (void)applicationDidFinishLaunching:(UIApplication *)application
{
	//Allocate and instatiate a new UINavigationController Object
	navController = [[UINavigationController alloc] init];
 
	//Allocate and initialize a First View Controller Object
	FirstViewController *firstViewController = [[FirstViewController alloc]init];
 
	//Push the first view controller onto the view controller stack without animation
	[navController pushViewController:firstViewController animated:NO];
 
	//Some memory management
	[firstViewController release];
 
	//Make it visible
	[window	addSubview:navController.view];
 
    // Override point for customization after application launch
    [window makeKeyAndVisible];
}

The first thing we’re doing in this function is instantiating the UINavigationController that we declared in our header. We pass it an alloc and init to allocate the appropriate amount of memory for it as well as an init to initialize it properly. The next thing we’re going to do is create a new FirstViewController object. Now you may be asking what a FirstViewController object is? That’s because we haven’t created it yet. So let’s go ahead and go to “File > New File” and add a new file that’s of the type UIViewController subclass. Make sure you check the little check box that says “With XIB for user interface”. This will give you an XIB file to work with instead of producing your interface programmatically. Now that we have our FirstViewControllerObject the only thing we have to do is import the header into the ViewDemoAppDelegate. So make sure to declare #import “FirstViewController.h” at the top of your code. Now onto the rest of the code in our application did finish launching method. The first thing we do with our allocated view controller is push it onto the navigation stack. Now because this is our first view we’re pushing onto the navigation stack we want to make sure to pass “NO” to the animated parameter because we don’t want to animate the root view when it’s pushed onto the stack. Now for some memory management. Once the FirstViewController is pushed onto the navigation stack the retain count on the object moves up to 2, therefore we can perform a release on the FirstViewController object so that the retain count stays at 1. Last thing we do in this method is add the view so our window so that it’s actually visible when we load the application.

Now we’re going to get into some interface builder stuff. Let’s start by opening up our FirstViewController.xib file in Interface Builder(or by just double clicking on it). You should see just a plain white view. Now in order to transition between views we need a button to press to actually transition between views. So let’s go ahead and add a UIButton to the view. Label the button anything you would like to to transition between views. Go ahead and save that file for now(we’ll come back to it later to connect the pointers). Next we’re going to create a new file in our project that’s a subclass of UIViewController. Again we’re going to make sure that “use XIB for user interface” is selected and press create. We’re going to name this view controller “SecondViewController” as it’s the one that we transition to from pressing the button on our first view controller. Once you create the new View Controller you should see it appear on the left hand side in your package explorer. Let’s go into our FirstViewController.h and add the following code.

#import <UIKit/UIKit.h>
@interface FirstViewController : UIViewController
{
	IBOutlet UIButton *transitionButton;
}
 
- (IBAction) pushViewContoller:(id) send;
 
@end

All we do here is create an IBOutlet for the UIButton we added to the XIB file and call it transition button. Then we create an IBAction method that will get called whenever the user presses inside the UIButton. Let’s open up our FirstViewController.m implementation file and implement the IBAction method like so…

#import "FirstViewController.h"
#import "SecondViewController.h"
 
@implementation FirstViewController
 
- (IBAction) pushViewContoller:(id) send
{
	//Allocate and instantiate the second view controller object
	SecondViewController *secondView = [[SecondViewController alloc] init];
 
	//Push the secondViewController onto the navigation stack
	[self.navigationController pushViewController:secondView animated:YES];
 
	//Some memory management
	[secondView release];
}

Now as you can see, we first provide our implementation with an import of the SecondViewController.h that we created earlier. We then proceed to allocate and instantiate our SecondViewController object. This time we’re going to push it onto our navigation stack and passing the YES parameter to our animated option because this time we do want it to be be animated when we press the button. After that we just provide some basic memory management to bring the retain count of the SecondViewController object back down to 1. That’s al the necessary code we need right now, however if you run this program right now you’ll notice that if you press the button on the first view controller it won’t really do anything. So let’s open back up our FirstViewController.xib file and hook up our IBOutlet and IBAction to our button that we created. After you’re finished hooking up these actions in the File’s owner connections inspector, the file’s owner connections inspector should look something like this..

Now you should be able to run the application and press the button and see the transition to the second view controller(which will be blank unless you added something to the nib) and press the back button in the navigation controller and transition back to the first screen.

If you’re having some troubles, here is the project and all the code. Download

Also again, if you have any questions feel free to leave them in the comments section.


Mar 9 2010

Installing Cocos2D for the iphone

I have recently started working on some Iphone games only to discover a spectacular 2D game engine on the iphone called Cocos2D. After reading their very impressive feature list and some blogs on how Cocos2D works, I decided to try it out for myself. Low and behold however that it wasn’t the easiest thing to install manually for iphone development. If you try and install cocos manually, you will run into countless errors and hassles while getting it up and running.

However, Cocos2D now sports a fancy shell script to get some Cocos2D templates up and running directly in Xcode with all the files pre-configured to start. To install these templates all you have to do is navigate to the cocos2D root directory on your filesystem using the terminal and then run this command.

./install_template.sh

You can then open Xcode and you should see the following screen ready to use.


Mar 1 2010

Iphone Programming Part 1 – Intro to Xcode and IB

First off before we start, here are a couple of things you will need to get started:

1. Mac running the latest version of xcode – This can be found on your install disc for leopard or snow leopard.

2. Latest version of the iphone SDK – This can be found at developer.apple.com

Now we can get started. Once you have xcode and the iphone SDK installed, open up xcode(Macintosh HD > developer > Applications). Once you have xcode installed, from the menu bar select file > new project. You should see a windows like the this one.

Select window based application from the iphone application option on the left hand side of the window. Once you select the window based application, xcode will prompt you to save the project. I named my project “LabelTester” and saved it under my personal iphone projects directory. Once you save the project, an xcode window should open up and look something like this.

You should see a combination of files here in the browser in the code browser. The first should be the CoreGraphics.framework. This is just a set of files provided by Apple that have all the code relevant to the core graphics libraries in Cocoa. The second is the foundation.framework. This is the library set for the foundation framework which is basically all the classes like NSArray, NSString and other foundation objects. The next item should be LabelTester.plist. The plist, or preference list, is a set of XML attributes that control how the application is handled. For the sake of this tutorial, you won’t need to open the plist. The next item should be the LabelTester.app file, which is the executable for your application. Once your application is deployed, all files and resources in your project will be located inside your app’s .app file. The next file is the LabelTester.pch file. This file is the prefix header for your application. The LabelTesterAppDelegate.h file is the next file in the list. This file is the header file for your application delegate. This is the starting for your application, the app delegate is what’s run by your main.m file when you app is launched. The .h file is of course the header file, which is basically the interface file that the .m file will implement. The next file is of course the LabelTesterAppDelegate.m. This file is the implementation file for the app delegate header. Next is the main.m file. This file is the application launcher for your app. It basically runs the app delegate. The next file is the Main Window.xib file. Anything with a nib/xib file extension is classified as an interface builder file and you open these files in the Interface builder application. Finally, the UIKit.framework. This library is used to correspond to all the UI elements on the iphone(text fields, buttons, etc).

Let’s start by opening up our Main Window.xib to setup our interface. Start by dragging a button from the libraries window onto your main View. Rename that button by double clicking on the button and change it to say “Update Label!”. Next, grab a text field and drag it just above the button. Expand the text field to fit the majority of the screen. Select the textfield and go into the attributes tab and enter into the placeholder field, “Enter Text to update Label”. Once that’s finished, drag a label onto the main window and change the text from “label” to “Label to Update”. Once that’s done you can save the interface builder file by pressing (command + s) and switch your view back to your xcode project.

Open up the LabelTesterAppDelegate.h file and change the file to reflect the following code.

#import 
 
@interface LabelTesterAppDelegate : NSObject
{
    UIWindow *window;
	IBOutlet UITextField *textField;
	IBOutlet UIButton *button;
	IBOutlet UILabel *label;
	IBAction *updateButtonPressed;
}
 
@property (nonatomic, retain) IBOutlet UIWindow *window;
@property (nonatomic, retain) IBOutlet UITextField *textField;
@property (nonatomic, retain) IBOutlet UILabel *label;
 
-(IBAction)updateButtonpressed:(id) sender;
 
@end

The first lines inside the curly braces will declare variables that we will be hooking up in Interface builder later. After the curly braces are closed, we have these property tags. These will allow us to have access to the objects and their data in the implementation file. After that we have an IBAction method declaration. This will eventually be hooked up to our button to run every time that our button is pressed. You can think of an IBAction method as an event handler in OBjective-C. Now let’s move onto our LabelTesterAppDelegate.m file and add the following method directly below out import statement.

#import "LabelTesterAppDelegate.h"
 
@implementation LabelTesterAppDelegate
 
@synthesize window;
@synthesize textField;
@synthesize label;
 
-(IBAction)updateButtonpressed:(id) sender
{
	//allocate a string and initialize it with the data from the text field
	NSString *string = textField.text;
 
	label.text = string;
}

Basically what we’re doing here is just creating that IBAction method that we declared in our interface file. Inside that method, we allocate a string to the value of our textField.text and then set the label equal to the string that we get from the textfield. That’s all the code we’ll need for now. Don’t forget to synthesize your objects below the implementation declaration in order to have access to the data you want. If you try and run this now, the application will run but will not function because the pointers in Interface Builder are not hooked up. So let’s go ahead and do that next. Save all your xcode files and open back up your Main Window.xib file in Interface Builder.

In order to setup a pointer in Interface builder, start by clicking on the application delegate and then the connections manager should appear. Beside each of the items that you created you should see a tiny circle. For each, click on the circle and drag the pointer to each of the elements in your window. This will create a pointer to that element. Now click on the button and then open it’s connection manager. Find the “touch up inside” connection and drag that pointer to the “file’s owner” section in the library and select “updateButtonPressed” when it appears. Once this is completed, you should see the connection screen look something like this.

That’s all folks, now if you run the application and enter some text into the text field, it will update the label to whatever text you entered. To download the whole project click here.

Cheers everyone and stay tuned for part 2!


Dec 13 2009

Intro to PHP – Creating a Basic Login System

Using a little knowledge of PHP and HTML you can build a simple log in system for your site. In order to correctly follow this tutorial you may want to have a good idea of basic HTML/PHP syntax as well as knowing some CSS. You should also have a basic understanding of how to create and use sessions($_SESSIONS) in PHP.

Alright let’s get started by just creating a basic log in window and place it in the center of the screen. First the log in window.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
	<head>
		<title>Sample Log In</title>
 
		<link rel="stylesheet" href="loginCSS.css" type="text/css" />
	</head>
	<body>
		<div id="outerLimit">
			<div id="container">
				<div id="innerLimit">
					<div id="loginBox">
						<form id="login" name="login" method="post" action="userAuth.php">
							<label for="username">Username:</label><br />
							<input type="text" id="username" name="username" size=40 /><br />
							<label for="password">Password:</label><br />
							<input type="password" id="password" name="password" size=40 /><br />
 
							<input type="submit" name="submit" value="Log In" />
						</form>
						<br />
					</div>
				</div>
			</div>
		</div>
	</body>
</html>

Next let’s move into a bit of the CSS. Basically we just want to create a window with a gray background so the fields are extremely easy to see. I called the CSS file in this case loginCSS.css but you can call it whatever you like as long as it’s referenced properly in the HTML section.

body
{
	background-color:white;
	min-height: 468px;
	min-width:552px;
	font-family:Helvetica;
}
 
a
{
	font-size:small;
}
 
#loginBox
{
	background-color: #e4e4e4;
	position:relative;
	top:25%;
	left:25%;
	width:300px;
	padding:15px;
}
 
#outerLimit
{
	height:100%;
	width:100%;
	display:table;
	vertical-align:middle;
}
 
#container
{
	position:relative;
	vertical-align:middle;
	display:table-cell;
	height:468px;
}
 
#innerLimit
{
	width:552px;
	height:468px;
	margin-left:auto;
	margin-right:auto;
}

As you can see, I just styled the page a little bit to make it a little bit easier for the user to use. Now that we have a basic page for the user to log in, we’ll also need a page, such as a dashboard, for the user to access when they enter in correct login criteria. In this case we’re just going to use a page that has a basic header telling the user they have logged in correctly. The page can look something like this.

 
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
	<head>
		<title>Sample Log In</title>
 
		<link rel="stylesheet" href="loginCSS.css" type="text/css" />
	</head>
	<body>
		<h1>You are now logged in!</h1>
		<a href="logout.php">Log Out Here</a>
	</body>
</html>

As you can see I have also included a log out link just below the h1 tag. If a user logs into the system we also want them to be able to log out. Next we’re going to create the SQL for our database. For this tutorial I’ll be using MySQL, however Oracle or SQL Server could also be used.

Note: If you’re going to use a different database then the code to connect to the database will be slightly different.

DROP TABLE IF EXISTS 'testDB'.'user'
 
CREATE TABLE 'testDB'.'user'
(
	'username' VARCHAR(10),
	'password' VARCHAR(10)
);
 
INSERT INTO 'testDB'.'user'
(username, password)
VALUES
('admin', 'password'),
('guest', 'password');

This is just a very simple database table that contains only a username and password. This script could obviously be modified to accept further fields of to encrypt the password field to increase the security of your system. Things like that will be out of the scope of this tutorial however.

Now that we have our environment set up we can start to use PHP to get data from the forms and compare them with the database. For the this tutorial we will only be using the POST method of retrieving data from forms. Using GET is often not recommended when getting sensitive data such as usernames and passwords. As you can see from the log in window, we have used the POST method to get the data, and when the form is submitted we are calling the userAuth.php file. Let’s go ahead and create that file now.

This block of code we will be using to check to see if the fields are blank. If they are we want to send them back to the login.html file to log back in again using the header() function. Next we want to enter all the configuration information to connect to the database and use some PHP functions to protect our site from SQL injection errors.

/*Create the variables to hold the database information*/
 
$dbName = "testDB";
 
/*Table name that we're checking against*/
 
$dbTable = "user";
 
/*Database username*/
 
$dbUsername = "DBUsername";
 
/*Database Password*/
 
$dbPassword = "DBPassword";
 
$username = $_POST(['username']);
$password = $_POST(['password']);
 
/*This next block is to prevent SQL injection hacks*/
$username = stripslashes($username);
$password = stripslashes($password);
 
$username = mysql_real_escape_string($username);
$password = mysql_real_escape_string($password);

I have put in default values into the variables. Variables such as $dbTable and $dbUsername will be subject to change based on your database configuration. These values will need to be filled in with correct values from your system. Next we’re going to be connecting to the database and opening a connection.

/*Connect to the Database*/
 
$connection = @mysql_connect("localhost", $dbUsername, $dbPassword) or die(mysql_error());
 
/*Select the database you want to access*/
 
$db = @mysql_select_db($dbName, $connection) or die(mysql_error());
 
/*Select statement from the database to see if the user is in the system*/
 
$sqlQuery = "SELECT COUNT(*) FROM $table_name WHERE username = '$username'
AND password = password('$password')";
 
/*Create a variable to hold the results of the SQL query*/
 
$result = @mysql_query($sqlQuery, $connection) or die(mysql_error());
 
/*Check the number of rows returned from the query*/
 
$num = mysql_num_rows($result);

Now we’re getting to the user authentication section. We’re now going to see if the number of rows that was selected is anything but 0. In theory it should ever only come back with 1 or 0 rows, however in systems where users can multiple accounts it’s good to keep it to != 0.

/*If the number of rows is not equal to 0 then authenticate the user*/
 
if ($num != 0)
{
	session_start();
 
	//Create a session for the username and password
	session_register($username);
	session_register($password);
 
	if(!session_is_registered($username))
	{
		header("location:login.html");
	}
	else
	{
		//because the user is authenticated move them to the dashboard
		header("Location: home.html");
	}
}
else
{
	header("Location: login.html");
	exit;
}
?>

We then register a session and store the username and password in the session. If the session has been registered correctly then you can send the user to the home screen. If the session is not registered correctly for some reason we don’t want the users accessing the system, so we send them back to the login screen to attempt to log in again.

That’s it, an entire login system. Of course this is just meant to give you the idea of the steps and should by no means be used in a real-world system as is. However you should have a firm understanding of how a basic login system works using PHP/MySQL and a little bit of HTML and CSS. As always if you have any questions/concerns feel free to leave a comment and I’ll get back to you asap.