- (void)fetchImages {
if (self.profileImages == nil) {
self.profileImages = [[NSMutableDictionary alloc] initWithCapacity:200];
}
dispatch_async(dispatch_get_global_queue(0, 0), ^{
for (id tweet in self.timeline) {
TWRequest *fetchUserImageRequest = [[TWRequest alloc] initWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"http://api.twitter.com/1/users/profile_image/%@", [tweet valueForKeyPath:@"user.screen_name"]]] parameters:nil requestMethod:TWRequestMethodGET];
[fetchUserImageRequest performRequestWithHandler:^(NSData *responseData, NSHTTPURLResponse *urlResponse, NSError *error) {
if ([urlResponse statusCode] == 200) {
[self.profileImages setObject:[UIImage imageWithData:responseData] forKey:[tweet valueForKeyPath:@"user.screen_name"]];
NSArray *indexPath = [NSArray arrayWithObject:[NSIndexPath indexPathForRow:[self.timeline indexOfObject:tweet] inSection:0]];
[self.tableView reloadRowsAtIndexPaths:indexPath withRowAnimation:UITableViewRowAnimationNone];
}
}];
}
});
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"FavoriteCell"];
// configure cell
id tweet = [self.timeline objectAtIndex:[indexPath row]];
UILabel *tweetLabel = (UILabel *)[cell viewWithTag:102];
tweetLabel.text = [tweet objectForKey:@"text"];
UILabel *usernameLabel = (UILabel *)[cell viewWithTag:101];
usernameLabel.text = [tweet valueForKeyPath:@"user.name"];
UIImageView *profileImage = (UIImageView *)[cell viewWithTag:100];
profileImage.image = [self.profileImages objectForKey:[tweet valueForKeyPath:@"user.screen_name"]];
UILabel *dateLabel = (UILabel *)[cell viewWithTag:103];
NSString *labelString = [[tweet objectForKey:@"created_at"] substringToIndex:10];
dateLabel.text = labelString;
return cell;
}
I get the timeline then want to get the profile images for all of users in the timeline. I need to loop through the tweets and get the image. I’m curious how I can determine when all of the images have been fetched then reload the tableview. As of now this isn’t happening. The TWRequest is running after the table is reloaded. What am I doing wrong here? Maybe there is a better way to do this?
Thanks a lot.
That’s because [TWRequest performRequestWithHandler:] is an async method. Why do you need to reload the entire table? Why not just reload the cell when you get a image (in the end of your handler block).
If you really want to reload the entire table just keep a count of all your finished requests, and reload the table when all is done.
If you want to reload a single cell you can do something like: