How To Create an App Like Instagram With a Web Service Backend – Part 1/2

This is a blog post by iOS Tutorial Team member Marin Todorov, a software developer with 12+ years of experience, an independent iOS developer and the creator of Touch Code Magazine. There’s no doubt photography apps have huge momentum on the App Store. With the iPhone 4’s awesome camera and fast processor, taking photos and […] By Marin Todorov.

Leave a rating/review
Save for later
Share
You are currently viewing page 2 of 5 of this article. Click here to view the first page.

Setting Up the Web API

Now for the other side of the project – the web API. For this, you will need an HTTP server and FTP access to it, and also access to a MySQL server. If you don’t already have those on your Mac, check the link at the top of the article for more details on setting up a local test server on your Mac.

I’ve also prepared a startup project for the web API, so once you have the web server running, go ahead and download the API startup project. Extract the contents of the ZIP file to a location on your hard drive.

The extracted ZIP should contain a few PHP files and a folder named “upload.” The main API file is index.php, and it’s the one you’re going to call from the iPhone app. In api.php, you’re going to add few simple functions to process the user requests, and lib.php contains a couple of functions that will help you with this.

One of them, a function called query, will help you avoid writing too much code. It takes an SQL query and a list of parameters as input, and returns an array containing the results of the SQL query. There’s also a function called thumb that scales down an image and saves the thumbnail.

Upload the folder with the api files to a location on your web server that can be accessed via a browser. Rename the folder to “iReporter,” since that will make things easier to identify. (If you’re doing this on your own machine at home, you can of course just copy the files in Finder to your web folder.) Make sure that the “upload” folder is writable via your PHP scripts, as you’ll be using the folder to save uploaded photos.

Note: You’ll be modifying some of the PHP files for the web service as you proceed through the tutorial. Do note that if you don’t have the web server set up on your Mac and are using a remote server, you’ll need to re-upload the modified files to the server each time you modify them.

Finally, set up the database for the web API. You need two simple tables – one to hold the username and passwords and one to hold the photos. The database table structures are shown below (it’s pretty simple):

SQL database structure

Here’s the SQL file to create the database tables (name the database “iReport”).

Now take one extra step: open up lib.php in your text editor of choice, and have a look at the first couple of lines of code. Depending on how you set up your MySQL server (or how it’s set on your hosting server), you need to edit this code so that PHP knows how to connect to your database server.

The first function, mysqli_connect, takes three parameters. Fill in this information: the first parameter is the name of the database server (leave “localhost” if you’re connecting to a server on your own computer), the second is the MySQL username, and the third is the password. I’ve input some default values working with a blank local installation of MySQL, but as mentioned, you might need to edit those to work with your setup.

On the second line of lib.php, there’s the mysqli_select_db function that takes two parameters: the already-active link to the database server, and the name of the database. If you called your database something other than iReport, change the database name here.

Awesome! You now have skeleton iPhone and web service projects. All that’s left is to write some code to get them to work together.

Registering Users to the Web Service

The plan for the app is to let users upload photos only after they have registered with the app. So the app workflow will go like this:

App workflow

Let’s start with implementing the registration and login to the server. Open up index.php in your favorite text editor. On the line where it says “//API”, add a check for all the possible commands that the API will handle.

Start with register and login. Replace the comment “//API” with:

switch ($_POST['command']) {
	case "login": 
		login($_POST['username'], $_POST['password']); break;

	case "register":
		register($_POST['username'], $_POST['password']); break;
	
}

If the POST parameter named “command” holds the login value, you pass the username and password POST parameters to a function called login. The register parameter is treated pretty much the same way, except that the function called is named register. If the client asks for a command the API doesn’t expect, the code execution will simply reach the exit() command at the end of the source file, and no response will be sent to the client.

Note: Don’t panic, we won’t be passing or storing the password as cleartext. (And neither should you!) More on this later :]

Now start with the register command. Open up api.php and add a little helper function for returning errors to the client (the iPhone app). Add this function to api.php within the PHP script tags (“<?” and “?>”):

function errorJson($msg){
	print json_encode(array('error'=>$msg));
	exit();
}

Since the iPhone app expects only JSON responses, you’ll use this little function, which takes a text message and turns it into a JSON response. json_encode is the PHP function that converts PHP objects to JSON – you just feed it an array with the error message, and that’s all.

Now proceed with the register function. First, check if the username exists already. Add the following code to api.php:

function register($user, $pass) {
	//check if username exists
	$login = query("SELECT username FROM login WHERE username='%s' limit 1", $user);
	if (count($login['result'])>0) {
		errorJson('Username already exists');
	}
	
}

On the first line, you create an SQL query to check if there’s a record in the login table with the username given. If there are results, you call errorJson, since you cannot register a user if the username already exists. And that pretty much ends the script, as errorJson dumps the error message and exits the program execution.

Note how the count function in PHP was used to check if there were any results – count returns the number of elements in an array.

OK, so things aren’t so difficult. Add the following to the end of the register method (before the closing curly bracket):

//try to register the user
$result = query("INSERT INTO login(username, pass) VALUES('%s','%s')", $user, $pass);
if (!$result['error']) {
	//success
	login($user, $pass);
} else {
	//error
	errorJson('Registration failed');
}

You use the query helper function again with an SQL command trying to insert a new record to the database. If the query doesn’t return an error (AKA, big success for you) then you just call login.

Why do you call login? Well, you’d like the user to be logged in after successful registration, so why not combine both into one call to the API, right? OK. Time to move to the login function. Wow, you’re moving ahead quite quickly :]

Here’s the whole login function. Add it to api.php, immediately after the register function:

function login($user, $pass) {
	$result = query("SELECT IdUser, username FROM login WHERE username='%s' AND pass='%s' limit 1", $user, $pass);

	if (count($result['result'])>0) {
		//authorized
		$_SESSION['IdUser'] = $result['result'][0]['IdUser'];
		print json_encode($result);
	} else {
		//not authorized
		errorJson('Authorization failed');
	}
}

That looks pretty similar to what you already did for register, right?

You run a SELECT SQL command on the login table, and then you check the count of the returned results. If any were found, you have a successful login. Then to create a server session for the logged user, you store their IdUser to the PHP session.

$_SESSION is a special array – everything you store inside will be persisted between different script executions – but only when they were made by the same client. So what you store in the SESSION array is the value of “$result[‘result’][0][‘IdUser’]”, which in PHP reads “the value of the IdUser key of the first element of the array stored in the result key.” Or to put it simply, you store the user’s ID, so you know who they are in the following API calls.

Believe it or not, that’s all the PHP code you need to have users register and login to your web service.

Let’s move to the iPhone – because I know just how you’re feeling! ;]

Finally Objective-C!!!

Contributors

Over 300 content creators. Join our team.