cs193p – Assignment #5 Task #1

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

Your application must implement all the required tasks from the last assignment (and all the required tasks in this assignment) without doing any Flickr fetching or file system interactions in the main thread. Your user-interface should be responsive to the user at all times (i.e. the main thread should never be blocked).

Flickr is accessed twice. First when the data is loaded to populate the first table. Create a new dispatch queue and load the photos there. As soon is this is done return to the main queue and set the photos property:

- (void)viewDidLoad
{
    [super viewDidLoad];    
    dispatch_queue_t queue = dispatch_queue_create("Flickr Downloader", NULL);
    dispatch_async(queue, ^{
        NSArray *photos = [FlickrFetcher stanfordPhotos];
        dispatch_async(dispatch_get_main_queue(), ^{
            self.photos = photos;
        });
    });
}


… and when loading the photo itself. Create a dispatch queue to download the photo data. When the photo has been loaded completely and the URL did not change because the user clicked on another photo, return to the main queue and setup the photo in the scrollview:

- (void)resetImage
{
    if (self.scrollView) {
        ...        
        NSURL *imageURL = self.imageURL;
        dispatch_queue_t queue = dispatch_queue_create("Flickr Downloader", NULL);
        dispatch_async(queue, ^{
            NSData *imageData = [[NSData alloc] initWithContentsOfURL:self.imageURL];
            if (imageURL == self.imageURL) {
                dispatch_async(dispatch_get_main_queue(), ^{
                    UIImage *image = [[UIImage alloc] initWithData:imageData];
                    if (image) {
                        self.scrollView.zoomScale = 1.0;
                        self.scrollView.contentSize = image.size;
                        self.imageView.image = image;
                        self.imageView.frame = CGRectMake(0, 0, image.size.width, image.size.height);
                        [self setZoomScaleToFillScreen];
                    }
                });
            }
        });
    }
}

The complete code is available on github.

FacebooktwitterredditpinterestlinkedintumblrmailFacebooktwitterredditpinterestlinkedintumblrmail

Leave a Reply

Your email address will not be published.