Mobile App Development

An Intro to Web Services: How to Pull a JSON String From a Web Server for iOS

November 5, 2012

  • admin

Based on a fictional story:

Last week, I went to a motorcycle showroom to purchase a new motorcycle.

The owner of the store knows I’m an iOS developer, so instead of test driving motorcycles, we spent our time discussing a new iPhone app project. He had a database with a list of motorcycles and wanted to display them in an iPhone app.

Creating a static app is not really a good idea since the app needs to be updated regularly with new data as motorcycles come on and off the inventory list. That’s why we use an online database!

The only way to get data from that database is by using Web Services.

There are two famous ways to do that: Using XML or JSON.

In this tutorial you’ll learn how to pull a JSON string from a web server.

First of all let’s see what a JSON string looks like:

An example of a JSON array holding 4 strings would look something like this:
[“one”,”two”,”three”,”four”];

Now if you have a dictionary with key/value pairs, you’ll see something like this:
{“name” : “dani” , “age” : 22}

Cool and simple, isn’t it?

Now that we have a simple understanding of JSON strings, we’ll assume that same guy created the back-end for this app where he filed all information in an online database. In addition to that, he used PHP to write the query needed to get the list of all motorcycles available with their related information accordingly.

First of all, let’s see how will we receive our JSON string:

[{“motorcycle_manufacturer”:”BMW”,”motorcycle_model”:”F650″},{“motorcycle_manufacturer”:”Ducati”,”motorcycle_model”:”Monster”},{“motorcycle_manufacturer”:”Yamaha”,”motorcycle_model”:”Venture”},{“motorcycle_manufacturer”:”Honda”,”motorcycle_model”:”GoldWing”},{“motorcycle_manufacturer”:”Suzuki”,”motorcycle_model”:”SV650″}]

It’s a bit messy so let’s see that in a clearer way.

Go to: http://json.parser.online.fr

And paste the results.

This helps display our data in a more organized way.

Now we can say that we have an array of dictionaries. The main array consists of objects representing motorcycles. Each motorcycle has 2 keys, one for the motorcycle manufacturer & another for the motorcycle model.

We’re done with the back-end side; so let’s see how can we implement that in our iPhone app.

Here are the steps to create the app:

1-    Send a request.
2-    Parse the JSON response string.
3-    Log the results

We’ll do that asynchronously to avoid locking the main thread (thus freezing the UI) during the whole process.

Below is all the code we need to write:

//1
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0),
^{
//2
   NSURL *JSONURL = [NSURL URLWithString:@”http://daniarnaout.com/Motorcycles.php”];

//3
   NSData *JSONData = [NSData dataWithContentsOfURL:JSONURL];
NSError *error;

 //4
   NSArray *motorcyclesArray = [NSJSONSerialization JSONObjectWithData:JSONData options:NSJSONReadingAllowFragments error:&error];

   //5
   if (!error)
{
for (NSDictionary *motorcycle in motorcyclesArray)
  NSLog(@”Manufacturer:%@ tt Model:%@ n”,[motorcycle objectForKey:@”motorcycle_manufacturer”],[motorcycle objectForKey:@”motorcycle_model”]);
}
  //6
   else
       NSLog(@”Error: %@”,[error localizedDescription]);

});

  1. Use an asynchronous block (GCD).
  2. Create the request URL.
  3. Store the response in an NSData object.
  4. Parse the JSON data using the native NSJSONSerialization class.
  5. Log errors if there are any.
  6. Log data to the screen.

* NSJSONSerialization is available for iOS5+.

Run your app and you’ll get this result:

And that’s how you use web services.

What’s next:

Remember, we are only logging results. In real applications, you’ll have to view this data in a UITableView or another type of controller with much more information such as images.

You can refer to Felipe’s previous tutorial about how to asynchronously load images into a table view.