I'm using AFNetworking to download rss feed image set to table view. Following is the code I'm using.
- (UITableViewCell *)tableView:(UITableview *)tableView cellForItemAtIndexPath:(NSIndexPath *)indexPath;
{
Cell *cell = [cv dequeueReusableCellWithReuseIdentifier:@"MY_CELL" forIndexPath:indexPath];
NSString *wallpaperLink = [af setThumbString:[[feeds objectAtIndex:indexPath.row] objectForKey: @"wallpaper"]];
//AfNetwork Download
AFHTTPRequestOperation *requestOperation = [[AFHTTPRequestOperation alloc] initWithRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:wallpaperLink]]];
requestOperation.responseSerializer = [AFImageResponseSerializer serializer];
[requestOperation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
//Set Cell Image from response
cell.imageView.image = responseObject;
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(@"Image error: %@", error);
}];
[requestOperation start];
return cell;
}
But when I go through some tutorials I realise that this is not the way to download asynchronous images with AFNetworking. Can someone tell me for my code, how to download & add the responseobject
to cell.imageView.image
???
I do it that way to avoid memory leaks:
NSURL *url = [NSURL URLWithString:@"http:url..."];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
UIImage *placeholderImage = [UIImage imageNamed:@"your_placeholder"];
__weak UITableViewCell *weakCell = cell;
[cell.imageView setImageWithURLRequest:request
placeholderImage:placeholderImage
success:^(NSURLRequest *request, NSHTTPURLResponse *response, UIImage *image) {
weakCell.imageView.image = image;
[weakCell setNeedsLayout];
} failure:nil];
It works fine with AFNetworking 2.
As @Greg suggest in a comment:
You have to add #import "UIImageView+AFNetworking.h".
If you are using AFNetworking, why not use the UIImageView+AFNetworking category? Just import UIImageView+AFNetworking.h and use this method:
- (void)setImageWithURLRequest:(NSURLRequest *)urlRequest
placeholderImage:(UIImage *)placeholderImage
success:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, UIImage *image))success
failure:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error))failure;
Edit: Don't forget to call setNeedsLayout
on the cell after you set the image!
When you are doing asynchronous image downloading, you can't get the result image on UITableViewCell
immediately. So, You should download the images and show them using array of downloaded image as per tableView
indexPath
.
Please refer this link to download image using lazy-loading and display it in UITableViewCell
.
Thanks!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With