Tuesday, June 21, 2011

Creating a REST Web Service App with Rotten Tomatoes API and SBJson Framework

We will create an app that will display a list of upcoming movies and their review scores in a table view. We will get our data from Rotten Tomatoes my favorite movie review site. But to be able to access their web service, we would need our own API key. We can get one by registering here: http://developer.rottentomatoes.com/


The Rotten Tomatoes API uses a RESTful service and it returns a JSON response. So to parse our response we would need to use the SBJson framework


Now, lets get started. Create a view based application in xcode. Name it "movies".



Edit moviesViewController.h:
Notice that we modified it to be a subclass of UITableViewController.


Edit moviesViewController.m:



Here, we create our URL string to communicate with the rotten tomatoes API. Just replace the blackened out portion with your own API key. This string is turned into an NSURL object by calling the URLWithString method. Then, we create JsonString to receive our response, by calling the initWithContentsOfURL. You may uncomment the NSLog to view the structure of the JSON string returned to us by the web service. 

Next we copy our SBJson files into our classes folder. Then import "JSON.h" in our moviesViewController.m, so we can create our SBJsonParser *parser object. Then we call its objectWithString: method, where we pass JsonString (our response string). This returns an NSDictionary object which we pass to our ivar dictionaryJson. We then release our parser because we don't need it anymore. Simple isn't it?

After that we grab an array of movies from our dictionaryJson. This is now the list of upcoming movies we will be displaying in our table view. 

So lets implement our table view delegate methods.
In numberOfRowsInSection, we just return the number of objects stored in the movies array. Then in cellForRowAtIndexPath, we get a particular movie from our movies array, then we get its title. Then we get its rating, which returns a critics score and an audience score. We grab the critics score in particular. We then display the movie title in the table view cell's textLabel property, and the critic's score in the cell's detailTextLabel property. Easy right?

Don't forget in our dealloc add:
[movies release];

Then we go to our moviesAppDelegate.m:

Here we just create our moviesViewController. Give it a title. Then make it the root view controller of a UINavigationController.  We then release our instance of moviesViewController after passing it to the navigation controller. Then we add the navigation controller's view to our window.

Make sure #import "moviesViewController.h" is present at the top of our moviesAppDelegate.m. 

Build and Run! Now we can plan our next movie using this simple app! Enjoy!





No comments:

Post a Comment