-3

I'm filling a UITableView with some categories. Ideally, I want to fetch an image corresponding to this category from Flickr. I wrote the code below:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    [self loadFlickr];

    NSLog(@"Flickr array is %@", self.photoUrls);

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
    if (cell == nil)
        cell = [[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:@"cell"];

    UIView *cellView=[[UIView alloc]initWithFrame:CGRectMake(5, 5, self.view.frame.size.width-10, 65)];
    [cell setBackgroundColor:[UIColor lightGrayColor]];
    [cellView setBackgroundColor:[UIColor whiteColor]];
    cellView.layer.cornerRadius = 5;
    cellView.layer.shadowOffset = CGSizeMake(-.2f, .2f);
    cellView.layer.shadowRadius = 1;
    UIBezierPath *path = [UIBezierPath bezierPathWithRect:cellView.bounds];
    cellView.layer.shadowPath = path.CGPath;
    cellView.layer.shadowOpacity = 0.2;

    UILabel *nameLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, 15, 100, 30)];
    nameLabel.text = [[self.ninjas[indexPath.row] name] capitalizedString];
    nameLabel.textColor = [UIColor blackColor];
    nameLabel.textAlignment = NSTextAlignmentLeft;
    [cellView addSubview:nameLabel];

    NSUserDefaults *standardUserDefaults = [NSUserDefaults standardUserDefaults];
    NSInteger unreadCounter = [standardUserDefaults integerForKey:[self.ninjas[indexPath.row] name]];

    UILabel *badgeLabel = [[UILabel alloc] initWithFrame:CGRectMake(self.view.frame.size.width-50, 15, 30, 30)];
    badgeLabel.text = [NSString stringWithFormat:@"%d", unreadCounter];
    badgeLabel.backgroundColor = [UIColor darkGrayColor];
    badgeLabel.textColor = [UIColor whiteColor];
    badgeLabel.textAlignment = NSTextAlignmentCenter;
    badgeLabel.layer.masksToBounds = YES;
    badgeLabel.layer.cornerRadius = 5;
    [cellView addSubview:badgeLabel];

    [cell addSubview:cellView];

    return cell;
}

- (void)loadFlickr {

    NSString *FlickrAPIKey = @"API_KEY";
    NSString *query = @"Google";

    NSUserDefaults *standardUserDefaults = [NSUserDefaults standardUserDefaults];
    NSString *accessToken = [standardUserDefaults objectForKey:@"AccessToken"];

    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"https://api.flickr.com/services/rest/?method=flickr.photos.search&api_key=%@&tags=%@&per_page=15&format=json&nojsoncallback=1", FlickrAPIKey, query]]];

    NSMutableURLRequest *mutableRequest = [request mutableCopy];

    request = [mutableRequest copy];

    AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
    operation.responseSerializer = [AFJSONResponseSerializer serializer];

    [operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {

        NSDictionary *results = responseObject;

        // Build an array from the dictionary for easy access to each entry
        NSArray *photos = [[results objectForKey:@"photos"] objectForKey:@"photo"];

        NSLog(@"photos is: %@", photos);

        NSMutableArray *tempUrls = [[NSMutableArray alloc] init];

        // Loop through each entry in the dictionary...
        for (NSDictionary *photo in photos)
        {
            // Get title of the image
            NSString *title = [photo objectForKey:@"title"];

            NSLog(@"title is: %@", title);

            NSString *photoURLString = [NSString stringWithFormat:@"https://farm%@.static.flickr.com/%@/%@_%@_m.jpg", [photo objectForKey:@"farm"], [photo objectForKey:@"server"], [photo objectForKey:@"id"], [photo objectForKey:@"secret"]];

            [tempUrls addObject:photoURLString];
        }

        NSLog(@"tempUrls is %@", tempUrls);

        self.photoUrls = [[NSArray alloc] initWithArray:tempUrls];

        NSLog(@"photoUrls is %@", self.photoUrls);

        tempUrls = nil;

    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {

        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Error Retrieving Pictures"
                                                        message:[error localizedDescription]
                                                       delegate:nil
                                              cancelButtonTitle:@"Ok"
                                              otherButtonTitles:nil];
        [alertView show];
    }];

    [operation start];
}

NSLog(@"photoUrls is %@", self.photoUrls); prints out just fine, but when I do NSLog(@"Flickr array is %@", self.photoUrls); it prints photoUrls is (null). What am I doing wrong?

user4334509
  • 125
  • 2
  • 10

1 Answers1

0
  1. cellForRowAtIndexPath is not the right place to perform a network request, and you will be calling the method for each cell.
  2. [self loadFlickr]; should be called in viewDidLoad.
  3. When you're done fetching reload the datasource with [self.tableView reloadData];
meda
  • 45,103
  • 14
  • 92
  • 122
  • 1
    These are all fine comments but none of them actually answer the question. – rmaddy Jan 01 '15 at 22:57
  • @rmaddy which part did I miss? – meda Jan 01 '15 at 22:57
  • You missed the question - why does the `NSLog` at the start of `cellForRow...` (after the call to `loadFlickr`) show `null` but the `NSLog` in the completion block near the end of `loadFlickr` show expected output. – rmaddy Jan 01 '15 at 22:59
  • @rmaddy hence my third point to reload the tableView, it wont be null – meda Jan 02 '15 at 00:00