cs193p – Assignment #6 Task #3

Please note, this blog entry is from a previous course. You might want to check out the current one.

Add a thumbnail image (FlickrFetcherPhotoFormatSquare) of each spot to every row in any table view that shows a list of spots. In addition …
a. Don’t ask Flickr for the image data of thumbnails that never appear on screen (i.e. fetch thumbnail image data only on demand).
b. Don’t block your main thread waiting for Flickr to give you a thumbnail’s data.
c. Never ask Flickr for the same thumbnail twice (cache the thumbnails’ data in your Core Data database).

To be able to display the thumbnail, we need its URL, which is currently missing in the core data 🙁 … add a new string attribute to the Photo entity, recreate its NSManagedObject subclass and set it in its category:

+ (Photo *)photoWithFlickrInfo:(NSDictionary *)photoDictionary
        inManagedObjectContext:(NSManagedObjectContext *)context
{
        ...
        photo.thumbnailURL = [[FlickrFetcher urlForPhoto:photoDictionary
                                                  format:FlickrPhotoFormatSquare] absoluteString];
        ...
}


Don’t forget to remove the app from the simulator/device, because of the changed model …

When there is already thumbnail data in core data, just use it. Otherwise load the file asynchronously. When finished add it to the current photo and display it …

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    ...
    cell.imageView.image = [UIImage imageWithData:photo.thumbnail];    
    if (!cell.imageView.image) {
        dispatch_queue_t q = dispatch_queue_create("Thumbnail Flickr Photo", 0);
        dispatch_async(q, ^{
            NSData *imageData = [[NSData alloc] initWithContentsOfURL:[NSURL URLWithString:photo.thumbnailURL]];
            [photo.managedObjectContext performBlock:^{
                photo.thumbnail = imageData;
                dispatch_async(dispatch_get_main_queue(), ^{
                    [cell setNeedsLayout];
                });
            }];
        });
    }
    return cell;
}

The complete code is available on github.

FacebooktwitterredditpinterestlinkedintumblrmailFacebooktwitterredditpinterestlinkedintumblrmail

Leave a Reply

Your email address will not be published.