iPhone JSON Flickr Tutorial – Part 2

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.

  1. 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:

1
2
3
4
5
// 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 farmserverid 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 fileJSONFlickrViewController.m as follows:

 
@interface JSONFlickrViewController : UIViewController <UITableViewDelegate, UITableViewDataSource>
{
  UITableView     *theTableView;
  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 setDelegate:self];
[theTableView setDataSource:self];
[theTableView setRowHeight:80];
[theTableView setBackgroundColor:[UIColor grayColor]];
[theTableView setSeparatorStyle:UITableViewCellSeparatorStyleNone];
[self.view addSubview:theTableView];
...

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 
{
  return 1;
}
 
- (NSInteger)tableView:(UITableView *)tableView 
      numberOfRowsInSection:(NSInteger)section 
{
  return [photoTitles count];
}
 
- (UITableViewCell *)tableView:(UITableView *)tableView 
      cellForRowAtIndexPath:(NSIndexPath *)indexPath 
{
  UITableViewCell *cell = 
      [tableView dequeueReusableCellWithIdentifier:@"cachedCell"];
 
if (cell == nil)
    cell = [[[UITableViewCell alloc] 
      initWithFrame:CGRectZero reuseIdentifier:@"cachedCell"] autorelease];
 
#if __IPHONE_3_0
  cell.textLabel.text = [photoTitles objectAtIndex:indexPath.row];
  cell.textLabel.font = [UIFont systemFontOfSize:13.0];
#else
  cell.text = [photoTitles objectAtIndex:indexPath.row];
  cell.font = [UIFont systemFontOfSize:13.0];
#endif
 
  NSData *imageData = [photoSmallImageData objectAtIndex:indexPath.row];
 
#if __IPHONE_3_0
  cell.imageView.image = [UIImage imageWithData:imageData];
#else
  cell.image = [UIImage imageWithData:imageData];
#endif
 
  return cell;
}

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 photoTitlesarray. 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
[theTableView reloadData];
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
  1. iPhone, JSON and Flickr Tutorial – Part 1
  2. iPhone, JSON and Flickr Tutorial – Part 3
  3. Download iPhone, JSON and Flickr – Part 2 Xcode Project
  4. Get Flickr API key
  5. Flickr API documentation
  6. Download JSON framework
  7. JSON Framework Google Group
  8. Stig Brautaset’s Blog

Stay tuned for Part 3 of the iPhone, JSON and Flickr tutorial…

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值