Welcome to the second tutorial in this three part series on using the iPhone SDK, JSON and Flickr. In the first tutorial we covered the basics for setting up the JSON framework within your projects, registering to get Flickr API key, and writing some code to asynchronously fetch images and their accompanying titles from Flickr.
The application created in Part 1 had no UI to speak of, the only output was debug information written directly to the console as a test case to verify we could successfully request and download images using JSON and Flickr.
The video shown in Part 1 that highlights the finished application, developed over the course of these three tutorials, is displayed below if you need a refresher:
Download iPhone JSON Xcode Project File
You may find it helpful to download the Xcode project and walk through the source code as you read this tutorial.
- Download iPhone, JSON and Flickr – Part 2 Xcode project
Flickr JSON Data
Let’s begin by taking a closer look at the data returned from Flickr and the resulting dictionary that the JSON framework creates for us.
The method that we wrote in Part 1 for receiving date from Flickr, didReceiveData, begins with the following two lines:
// Store incoming data into a string
NSString *jsonString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
// Create a dictionary from the JSON string
NSDictionary *results = [jsonString JSONValue];
Below is a screenshot of the jsonString (line 2 from above) as shown in the Xcode console. Everything you need is here, however, it would be a mess to parse this ourselves.
With one line of code (on line 5 above) the JSON framework will convert the string format into a dictionary. The image below shows a formatted output of the JSON, which better describes the dictionary – photos is a dictionary, and looking down to the fifth entry in the list, the key-value pair, with the key photo is an array of each photo returned from Flickr based on the search query we request. Each entry in the photo array is a dictionary as well, with keys “id”, “owner”, “secret”, “server”, etc.
With the help of the JSON framework and conversion to a dictionary, accessing the contents from Flickr becomes as easy as requesting key-value pairs. For example, to loop through the titles for each image we begin by creating a reference to the array of photos as listed here:
NSArray *photos = [[results objectForKey:@"photos"] objectForKey:@"photo"];
With the array in hand, we now access each entry in the array and create an NSString object from the key-value pair with the key “title”:
for (NSDictionary *photo in photos)
// Get title of the image
NSString *title = [photo objectForKey:@"title"];
Building Paths to the Images
Let’s review how to build the path to images hosted on Flickr, based on values in the JSON return data. To access an image, the path looks like this: http://farmX.static.flickr.com/server/id_secret.jpg, where each of the bold entries in the path is mapped to one of the entries in the photos array (see the image above).
For example, in the return results shown below, note the values for farm, server, id and secret.
Using the values above, we can now build a path to each image. For example, the path for the image data shown above looks as follows (screenshot of the Xcode console):
Define Table for Images and Titles
Let’s add code to the previous project to store the images and title returned from Flickr into a table. The result will look as shown below:
Begin by adding a tableview to JSONFlickrViewController to the implementation file JSONFlickrViewController.m as follows:
@interface JSONFlickrViewController : UIViewController <UITableViewDelegate, UITableViewDataSource>
NSMutableArray *photoTitles; // Titles of images
NSMutableArray *photoSmallImageData; // Image data (thumbnail)
NSMutableArray *photoURLsLargeImage; // URL to larger image
Now, inside the same file, we need to add code to initialize the table. In the init method, we’ll create the table as follows:
// Create table view
theTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 240, 320, 220)];
[theTableView setBackgroundColor:[UIColor grayColor]];
Notice the row height set to 80, as the Flickr thumbnail images are 75 x 75 pixels. The extra space allows some room around the image so it fits snuggly within the table row, yet has some visual padding.
Populate Table with Flickr Content
Next up is adding content to the table – we want an image on the left and its title text on the right. The code follows:
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
- (NSInteger)tableView:(UITableView *)tableView
return [photoTitles count];
- (UITableViewCell *)tableView:(UITableView *)tableView
UITableViewCell *cell =
if (cell == nil)
cell = [[[UITableViewCell alloc]
initWithFrame:CGRectZero reuseIdentifier:@"cachedCell"] autorelease];
cell.textLabel.text = [photoTitles objectAtIndex:indexPath.row];
cell.textLabel.font = [UIFont systemFontOfSize:13.0];
cell.text = [photoTitles objectAtIndex:indexPath.row];
cell.font = [UIFont systemFontOfSize:13.0];
NSData *imageData = [photoSmallImageData objectAtIndex:indexPath.row];
cell.imageView.image = [UIImage imageWithData:imageData];
cell.image = [UIImage imageWithData:imageData];
Most of this code is
straightforward – there is one section in the table, the number of rows in that sole section is equal to the number of entries in the photoTitles array (which we built from the Flickr return data).
For each row in the table, we set the cell text by accessing the desired row from the photoTitles array. For the cell image we create a UIImage object from the photoSmallImageData array (again, from data we retreived from Flickr).
The last step is to make a call to populate the tableview once the data has been downloaded. Inside the method didReceiveData, at the bottom, once we’ve built all the internal arrays to hold the Flikr results, we make a request to reload the table data (see the project source code for the big picture of where this line of code lives):
// Update the table with data
Looking Ahead to Part 3
At this point we can request data from Flickr, store the results into internal variables and populate and display a table of images and descriptions.
There are two things we need to finish before we can call this application complete. First, we need to add a textfield so users can input their desired search strings. Second, when a user taps on a row in the table, we want to display a larger version of the image above the table. We’ll do this by sliding a view onto the screen from right.
Summary of Links
- iPhone, JSON and Flickr Tutorial – Part 1
- iPhone, JSON and Flickr Tutorial – Part 3
- Download iPhone, JSON and Flickr – Part 2 Xcode Project
- Get Flickr API key
- Flickr API documentation
- Download JSON framework
- Stig Brautaset’s Blog
Stay tuned for Part 3 of the iPhone, JSON and Flickr tutorial…