Hostinicon
GET HOSTING FROM $3.95/MO PLUS A FREE YEAR ON TUTS+ (RRP $180). HURRY OFFER LIMITED. Check it out
Advertisement

iPhone SDK: First Steps With JSON Data Using the Twitter API

by
Gift

Get a free year on Tuts+ this month when you purchase a Siteground hosting plan from $3.95/mo

Web accessible APIs provide a wealth of resources for extending the functionality of your iPhone apps. These APIs tend to be consumed in two primary data formats: XML and JSON. The iPhone SDK has built-in support for XML parsing, and this will be covered in a separate tutorial. In this tutorial, we will be focusing on adding JSON support to your iOS applications by demonstrating how to create a Twitter reading client app.

JSON Twitter Client Final Preview

Introduction

The JSON Framework is an extremely popular framework. It is used to power a large portion of the commonly used apps on the App Store, including the Facebook app, the Google Maps app, and pretty much every single Twitter client out there.

Why JSON?

There are a couple of reason to chose JSON over XML. The primary reason JSON is preferred is because JSON files are generally smaller in file size than their XML counterparts, and this naturally results in less load time. Another reason worth considering is that Apple's Push Notification system works best with JSON payloads.

1. Getting Started

Creating an Xcode Project

  1. Create a new Xcode project of your choosing. I'm going to use the View-Based template.
    Creating a new JSON project in Xcode
  2. Download the JSON Framework here.

Adding the Framework

Adding the framework is simple. You just need to drag the files into your project. There is an option to link the library to your project, but that option is now deprecated and not supported.

  1. Drag the JSON folder from the DMG and drop it in your Xcode project. You can add it to the "Other Sources" group if you would like.
  2. Select the 'Copy items into destination group's folder' option when prompted.
    Adding the JSON Framework in Xcode
  3. Add:

    into the source files where you will be using the framework.

2. Using the JSON Library

A Sample JSON Message

The following is a sample JSON message representing what a person object might look like:

Parsing a JSON String

To parse the above, we first load the JSON message into an NSString:

From looking at the sample JSON message, we can see that data is encapsulated with both brackets (e.g. [ ] ) and braces (e.g. { } ). The brackets are arrays of data and the braces are the dictionaries of data. As you can see, we are able to nest arrays of dictionaries, and dictionary objects can contain arrays for multiple values.

In the example above, we have a dictionary for contact with keys such as firstname, lastname, etc. The address key points to another dictionary which contains its own key-value pairs. The phoneNumber key in the dictionary contains an array of dictionaries.

To parse an array we use:

To parse a Dictionary, we use:

Choose the one you need based on your root object. For example, if your API is returning a list of contacts, you would get back an Array of contacts dictionaries. Similarly, if you ask for a twitter timeline, you're getting back an array of tweets where each tweet is a dictionary.

Creating a JSON String

Creating a JSON string is very simple and straightforward. You create either an NSDictionary with the appropriate Keys and Values or an NSArray with the list of objects. This process is fairly similar to how we parsed the JSON in the previous step.

You would create a dictionary with your data.

Add your newly created data dictionary to its class

Then generate the JSON Representation of your class dictionary.

You can also create your arrays and nest dictionaries or arrays accordingly.

Note: There is no method in the JSON framework that will validate whether a message is valid JSON.

3. Putting It All Together

Let's create a simple iPhone app that shows a list of the last 5 tweets that contains mobtuts.

We're going to use the Twitter Search API for simplicity because it doesn't require authentication or authorization.

A Tweet

The URL for our request is:

This will return to us a dictionary result which contains an array of tweets.

To make life a little easier, let's concentrate on just the user's profile image url, the tweet text, and the user's twitter name.

A single resulting tweet looks like this:

We can see that we're looking for the "profile_image_url", "from_user", and "text" keys for our app.

The Parser

Let's create a simple JSON Parser and make the request from the API.

Twitter_SearchAppDelegate.h

Now we'll add the JSON framework to the import statements.

Twitter_SearchAppDelegate.m

From here, we'll modify didFinishLaunchingWithOptions method in the App Delegate and make an NSURLRequest to Twitter with the URL to grab the Tweets we want to process. We'll also set the App Delegate to be the NSURLRequest's delegate.

Now, since our App Delegate is the NSURLRequest's delegate, we must implement those delegate methods. We're primarily interested in being notified when the data is being sent to us and when the request is complete and there is no more data to receive.

This is where our parser is doing most of the work. It is parsing the JSON file and creating the array of tweets for us. We get the array and pass it on to the TableViewController to display it.

A Simple TableView

Now we simply use the array we created from the parser to display the data in our TableView.

Twitter_SearchViewController.h

TweetsTableViewController.m

In the controller, we first need to synthesize the property and then set the number of rows that we'll be displaying

Finally, we'll display the tweets by referencing their specific keys from the dictionary. From looking at the JSON string earlier, we know we're looking for the values associated with the "from_user", "profile_image_url", and "text" keys.

Additional Considerations

If you're planning on using either Three20 or httpriot, you do not need to add the JSON framework. Those project already include it in their code. If you're planning on using ASIHTTPRequest, the JSON framework is not included and you do need to add it yourself.

Advertisement