2015-01-01 5 views
-3

Я заполняю UITableView с некоторыми категориями. В идеале, я хочу получить изображение, соответствующее этой категории, от Flickr. Я написал код ниже:NSArray, дающий null в результате

- (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); печатает только штраф, но когда я NSLog(@"Flickr array is %@", self.photoUrls); печатает photoUrls is (null). Что я делаю не так?

+0

Это опечатка в 1 'NSLog' в конце вашего вопроса? – rmaddy

+0

В чем разница между двумя NSLogs, которые вы положили – meda

+0

Да, это было. Прости. – user4334509

ответ

0
  1. cellForRowAtIndexPath не является правильным местом для выполнения запроса сети , и будет вызывать метод для каждой ячейки.
  2. [self loadFlickr]; следует называть в viewDidLoad.
  3. Когда вы закончите выборки Обновить источник данных с [self.tableView reloadData];
+1

Все эти замечательные комментарии, но ни один из них не отвечает на вопрос. – rmaddy

+0

@rmaddy какой части я пропустил? – meda

+0

Вы упустили вопрос: почему «NSLog» в начале «cellForRow ...» (после вызова 'loadFlickr') показывает« null », но« NSLog »в блоке завершения в конце' loadFlickr 'показать ожидаемый результат. – rmaddy