iPhone JSON Flickr Tutorial – Part 1

http://iphonedevelopertips.com/networking/iphone-json-flickr-tutorial-part-1.html

 

Two consistently popular posts on iPhone Dev Tips are JSON Frameworks for iPhone Part 1 andPart 2. Seems a good time to revisit the combination of the iPhone and JSON, this time creating a complete working application.

This is part one of a three part series in which I’ll build a Flickr photo viewer, a pretty simple application, however, we’ll cover some interesting stuff with the primary goal of understanding the nuts and bolts of working with JSON to build a complete working application accessing web-services.

Let’s start by looking at the finished application – the video below shows the end result we’re after – it starts with a search box (UITextField) and an empty table. Once you enter a search string, the application will construct a URL to call a photo search method at Flickr. The return data will be used to populate a table with thumbnails images and any title associated with the photo.

As you browse the table, you can touch an image and a second request will be submitted to Flickr for a larger variation of the same image. The larger image will be displayed above the table. As you select additional rows in the table, the current image will slide off the screen and a new image will slide into place. Watch the video below, it’ll make more sense once you see everything pulled together.

 




 

Setting up JSON Framework

The library used in this application is one written by Stig Brautaset and hosted atcode.google.com. I’ve used this library in two applications that are in the App Store, Today’s Horoscope, free and paid. This is an excellent library, you can’t go wrong.

  1. Download the iPhone JSON framework

There are a few variations on the install process, the easiest and least prone to errors is to copy the source files directly into your project. In the project that is attached to this post, this is done for you, however, it’s shown here if you need to add the framework to an existing or future project.

  1. Open the dmg file from the download.
  2. Drag the JSON folder and drop it on the ‘Classes’ group in the ‘Groups & Files’ in your Xcode project.
  3. Check the “Copy items into destination group’s folder” option.
  4. You can now use #import “JSON.h” in your source files.
Xcode Project Download – Part 1

To keep this post to a manageable length, I’ll show only the code that is most pertinent to JSON, Flickr and the overall application flow, the code on the periphery you’ll be familiar with and you can browse through at any time in the project source code.

  1. Download iPhone, JSON and Flickr – Part 1 Xcode project
Get Flickr API Key

If you don’t already have a Flickr API key, that’s the next step.

  1. Get Flickr API key.

The key will be an alpha-numeric value that you pass into all requests when calling a Flickr API. You’ll need to replace the key in the project for this post with your own Flickr key. Once you have the key, you’ll need to copy/paste the same into the FlickrAPIKey variable in the fileJSONFlickrViewController.m.

NSString *const FlickrAPIKey = @"your-key-here";
Flickr APIs

Flickr has an impressive list of APIs you can access, take a look here Flickr API’s.

We’ll be using REST request format for calling Flickr, here is basic layout for how calls will look:

http://api.flickr.com/services/rest/?method=flickr.test.echo&name=value

For our interests, we want to search for photos, so the method we are after is:flickr.photos.search. The Flickr API page for this method is here.

The full URL we’ll pass to Flickr will look as follows:

NSString *urlString = 
  [NSString stringWithFormat:
     @"http://api.flickr.com/services/rest/?method=flickr.photos.search&api_key=%@&tags=%@&per_page=25&format=json&nojsoncallback=1", 
     FlickrAPIKey, text];

The parameters to the query are:

  1. api_key: your specific developer key
  2. tags: the search text
  3. per_page: the number of images to return
  4. format=json&nojsoncallback: request the results to be returned as JSON
Earth to Flickr, Come in Flickr

With our URL complete, our next step is to make sure we can talk to the appropriate Flickr API and retrieve images based on a search string.

We have a very basic application framework at this point, an App Delegate class and a bare bones view controller. The interface definition for the view controller follows:

@interface JSONFlickrViewController : UIViewController
{
  NSMutableArray  *photoTitles;         // Titles of images
  NSMutableArray  *photoSmallImageData; // Image data (thumbnail)
  NSMutableArray  *photoURLsLargeImage; // URL to larger image
}

At this point all we are concerned about is capturing the names of the images from Flickr, the image data for our thumbnail image and also, the URL’s for the larger images. The initialization code consists of allocating a view, initializing the arrays, and calling the method to search Flickr for photos matching a search string:

- (id)init
{
  if (self = [super init])
  {
    self.view = [[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease];
 
    // Initialize our arrays
    photoTitles = [[NSMutableArray alloc] init];
    photoSmallImageData = [[NSMutableArray alloc] init];
    photoURLsLargeImage = [[NSMutableArray alloc] init];
 
    // Notice that I am hard-coding the search tag at this point (@"iPhone")    
    [self searchFlickrPhotos:@"iPhone"];
 
  }
  return self;
}

The call to [self searchFlickrPhotos:@"iPhone"]; begins the process of creating the URL to call Flickr, which in turn will kick off an asynchronous request to download the image data.

-(void)searchFlickrPhotos:(NSString *)text
{
  // Build the string to call the Flickr API
  NSString *urlString = 
    [NSString stringWithFormat:
      @"http://api.flickr.com/services/rest/?method=flickr.photos.search&api_key=%@&tags=%@&per_page=15&format=json&nojsoncallback=1", FlickrAPIKey, text];
 
  // Create NSURL string from formatted string
  NSURL *url = [NSURL URLWithString:urlString];
 
  // Setup and start async download
  NSURLRequest *request = [[NSURLRequest alloc] initWithURL: url];
  NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
  [connection release];
  [request release];
 
}

At this point we’ve made our request to Flickr to search for photos that are tagged with the text “iPhone” From here, we need to process the incoming data. The method didReceiveData: is the callback that will deal with the incoming data. Within this method we’ll save the title of the image, the image data for the thumbnail as well as the URL for the large image. Here’s what that code looks like:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data 
{
  // 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];
 
  // Build an array from the dictionary for easy access to each entry
  NSArray *photos = [[results objectForKey:@"photos"] objectForKey:@"photo"];
 
  // Loop through each entry in the dictionary...
  for (NSDictionary *photo in photos)
  {
    // Get title of the image
    NSString *title = [photo objectForKey:@"title"];
 
    // Save the title to the photo titles array
    [photoTitles addObject:(title.length > 0 ? title : @"Untitled")];
 
    // Build the URL to where the image is stored (see the Flickr API)
    // In the format http://farmX.static.flickr.com/server/id_secret.jpg
    // Notice the "_s" which requests a "small" image 75 x 75 pixels
    NSString *photoURLString = 
      [NSString stringWithFormat:@"http://farm%@.static.flickr.com/%@/%@_%@_s.jpg", 
      [photo objectForKey:@"farm"], [photo objectForKey:@"server"], 
      [photo objectForKey:@"id"], [photo objectForKey:@"secret"]];
 
    NSLog(@"photoURLString: %@", photoURLString);
 
    // The performance (scrolling) of the table will be much better if we
    // build an array of the image data here, and then add this data as
    // the cell.image value (see cellForRowAtIndexPath:)
    [photoSmallImageData addObject:[NSData dataWithContentsOfURL:[NSURL URLWithString:photoURLString]]];
 
    // Build and save the URL to the large image so we can zoom
    // in on the image if requested
    photoURLString = 
      [NSString stringWithFormat:@"http://farm%@.static.flickr.com/%@/%@_%@_m.jpg", 
      [photo objectForKey:@"farm"], [photo objectForKey:@"server"], 
      [photo objectForKey:@"id"], [photo objectForKey:@"secret"]];
    [photoURLsLargeImage addObject:[NSURL URLWithString:photoURLString]];        
 
    NSLog(@"photoURLsLareImage: %@/n/n", photoURLString); 
  } 
}

Look closely at line 7: NSDictionary *results = [jsonString JSONValue]; which is where the magic occurs, converting the incoming JSON data into a dictionary, which makes our parsing the Flickr data as simple as working with key-value pairs. We’ll look closer at the JSON return values from Flickr, converting to a dictionary and building the arrays of image data in Part 2 of this tutorial.

Flickr Image Data

Notice in the code above how I added to NSLog statements to verify the return results. A partial listing of the output is shown below:

As one last sanity check, you can copy/paste a few of the links shown in the Xcode console into a browser window to see what photos Flickr is returning.

Looking Ahead to Part 2

In Part 2 of this tutorial we’ll start by looking at the raw data returned from Flickr and walk through how to map that information into dictionaries and arrays. We will also extend the current application to store the results from our query into a table. We’ll also add a textfield to the interface so we can search for photos matching any tag.

Summary of Links
  1. iPhone, JSON and Flickr Tutorial – Part 2
  2. iPhone, JSON and Flickr Tutorial – Part 3
  3. Download iPhone, JSON and Flickr – Part 1 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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值