Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AFNetworking UIImageView need scroll to load the images

I'm inserting images in a UITableViewCell with AFNetworking. The problem is that i need to scroll the table to see the images.

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell" forIndexPath:indexPath];
    Recipe *recipe = [self.fetchedResultsController objectAtIndexPath:indexPath];
    cell.textLabel.text = recipe.value;
    NSURL *url = [NSURL URLWithString:[BaseURLString stringByAppendingString:recipe.img]];
   [cell.imageView setImageWithURL:url];
    return cell;
}
like image 393
Godfather Avatar asked Feb 16 '23 01:02

Godfather


2 Answers

There is such a method already implemented by AFNetworking in UIImageView+AFNetworking category.

[imageView setImageWithURLRequest:request placeholderImage:nil success:^(NSURLRequest *request, NSHTTPURLResponse *response, UIImage *image) {
    blockImageView.image = image;
} failure:nil];

Note that if you pass in nil in success the image is set to the imageview you call the method on. In my case imageView.

So here i guess you can do reload data if you need.

like image 80
Peter Segerblom Avatar answered Mar 03 '23 03:03

Peter Segerblom


In addition to Peter Segerblom's answer, I would recommend using a __weak reference in place of the __block blockImageVariable variable to avoid a retain cycle.

If you just use __block, the copy of the imageView will never be deallocated and the count will always remain even after the tableView is gone because the pointer is referencing another memory address.

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    cell.textLabel.text = @"Cell text";

    NSURLRequest *request = [NSURLRequest requestWithURL:imageURL];
    __weak UITableView *weakTableView = tableView;
    __weak UITableViewCell *weakCell = cell;
    __weak UIImageView *weakImageView = cell.imageView;
    [cell.imageView setImageWithURLRequest:request
                          placeholderImage:placeholderImage
                                   success:^(NSURLRequest *request, NSHTTPURLResponse *response, UIImage *image) {
                                       weakImageView.image = image;
                                       if ([weakTableView.visibleCells containsObject:weakCell]) {
                                           [weakTableView reloadRowsAtIndexPaths:@[ indexPath ] withRowAnimation:UITableViewRowAnimationNone];
                                       }
                                 } failure:nil];

    return cell;
}
like image 22
pxpgraphics Avatar answered Mar 03 '23 03:03

pxpgraphics