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 5 of 5 of this article. Click here to view the first page.

I’m Ready for Some Files, Baby

Switching back to the web service, you're going to go on with the part of the web service that accepts photos submitted by the users and stores them on the server. First you need to add the code to handle the upload command.

Open up index.php and add a new case in the switch command:

case "upload":
	upload($_SESSION['IdUser'], $_FILES['file'], $_POST['title']);break;

In case the upload command of the API is being called, you take the user ID from the user session, and you send it to the upload function along with the submitted file (from the $_FILES array in PHP) and the title the user provided for that photo.

Ah! The upload function. No problem at all.

Open up api.php. Here's where you're going to add the aforementioned function. At the bottom of the file add this code:

function upload($id, $photoData, $title) {
	//check if a user ID is passed
	if (!$id) errorJson('Authorization required');
	
	//check if there was no error during the file upload
	if ($photoData['error']==0) {
		$result = query("INSERT INTO photos(IdUser,title) VALUES('%d','%s')", $id, $title);
		if (!$result['error']) {
			
			//inserted in the database, go on with file storage
			
		} else {
			errorJson('Upload database problem.'.$result['error']);
		}
	} else {
		errorJson('Upload malfunction');
	}
}

This is the first part of the code you need in order to do the photo upload. Let's see where you are:

  1. Since this is a protected method (i.e. accessible only to logged in users) you check if there is a user ID stored in the session (the $id parameter passed to the function).
  2. $photoData (an array) is being populated by PHP with the file upload details. You check the error key to see if the upload succeeded. If there was an error, there's no sense in going on with inserting data in the database.
  3. If the upload is OK, you go on with inserting the title of the photo and the user ID in the database.
  4. You're going to use the automatically-created ID in the database table “photos" as an identifier for the photo file itself. You'll see this in a moment.
  5. If the database insert was successful, you go on with saving the file – you see the comment where the code will be.

As you can see, every step in the upload process so far can fail in a different way, so you already have three if-else statements that use errorJson to return different fail responses. In decoupled systems (like your client-server app), much more can go wrong in the workflow compared to ordinary software, so having good error-handling logic is essential if you want to build even a moderately complicated application.

Now add the code to store the uploaded files on the server.

First you need to get hold of a link to the database, so you can get the automatically generated ID in the photos table. Luckily, lib.php already grabs a link to the database for you, so just use that. The link is called "$link" and is found in the global variable namespace.

Add the code and see how it works. Replace the "//inserted in the database…" comment with:

	//database link
	global $link;
	
	//get the last automatically generated ID
	$IdPhoto = mysqli_insert_id($link);
	
	//move the temporarily stored file to a convenient location
	if (move_uploaded_file($photoData['tmp_name'], "upload/".$IdPhoto.".jpg")) {
		//file moved, all good, generate thumbnail
		thumb("upload/".$IdPhoto.".jpg", 180);
		print json_encode(array('successful'=>1));
	} else {
		errorJson('Upload on server problem');
	};

You call mysqli_insert_id, which returns the last auto-generated ID in the database – namely, the ID of the newly saved photo record.

When you upload a file to the server using PHP, the file is saved to a temporary location on the server, and the path to that location is passed to the PHP script handling the upload via the $_FILES array. You then call move_uploaded_file, which (as the name describes pretty well) moves the newly uploaded photo file from its temporary location to the folder where you want it to be.

You rename the file, following the [database id].jpg format so that the file name always corresponds to the database ID for the file record. Then you call the nifty thumb function to generate a nice thumbnail of the full-size photo.

Finally, if all went well, you return a JSON response with the key "successful.” That lets the iPhone app know that all is well, the photo was uploaded successfully, and that it was saved to the system.

Where To Go From Here?

You have the app talking to the server and that's pretty cool, so you can play around a bit with sending data over and maybe adjusting the server response.

But, you are far from finished! When you're ready, Part 2 of this tutorial awaits, where you will develop all the cool functionality of the iPhone, allowing the user to take photos, apply effects and send them over to the server.

In the meantime, if you have any questions or comments please join the forum discussion below!

This is a blog post by iOS Tutorial Team member Marin Todorov, a software developer with 12+ years of experience, an independant iOS developer and the creator of Touch Code Magazine. You can also find me on

Contributors

Over 300 content creators. Join our team.