Skip to content
Alfie Hanssen edited this page Nov 23, 2013 · 2 revisions

Instead of NSLogging your errors and array, invoke your completionBlock and pass the error and array as arguments:

- (void)fetchPopularMediaWithCompletionBlock:(void (^)(NSArray *media, NSError *error))completionBlock
{
    NSString * endpoint = [NSString stringWithFormat:@"%@%@", POPULAR_MEDIA_ENDPOINT, INSTAGRAM_CLIENT_ID];
    
    NSURL *URL = [NSURL URLWithString:endpoint];
    NSURLRequest *request = [NSURLRequest requestWithURL:URL];
    
    // Use an NSURLSessionDataTask to asynchronously fetch JSON from Instagram's "popular media" endpoint
    
    __weak MediaManager * weakSelf = self;
    NSURLSession *session = [NSURLSession sharedSession];
    NSURLSessionDataTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
        
        // Check for errors related to the request and response
        // Call the requisite delegate methods
        
        if (error) {
            NSLog(@"Error: %@", error.localizedDescription);
        } else {
            
            NSDictionary *dictionary = [NSJSONSerialization JSONObjectWithData:data
                                                                       options:NSJSONReadingAllowFragments
                                                                         error:&error];
            if (error){
                NSLog(@"Error: %@", error.localizedDescription);
            } else {
                NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response;
                if (httpResponse.statusCode == 200) {
                    NSArray *media = [weakSelf mediaFromResponse:dictionary];
                    NSLog(@"Success! %@", media);
                } else {
                    error = [NSError errorFromResponse:dictionary];
                    NSLog(@"Error: %@", error.localizedDescription);
                }
            }
        }
        
    }];
    [task resume];
}

And log the error and mediaArray arguments in your completionBlock in PopularMediaViewController:

- (void)updateContent
{
    [self.mediaManager fetchPopularMediaWithCompletionBlock:^(NSArray *media, NSError *error) {

        // NSLog media and error here...

    }];
}