我使用AFNetworking将rss Feed图像集下载到表格视图。以下是我正在使用的代码。
- (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;
}
但是当我浏览一些教程时,我意识到这不是用AFNetworking下载异步图像的方法。有人可以告诉我我的代码,如何下载&将responseobject
添加到cell.imageView.image
???
答案 0 :(得分:21)
我这样做是为了避免内存泄漏:
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];
AFNetworking 2可以正常使用。
@Greg在评论中建议:
您必须添加#import "UIImageView+AFNetworking.h".
答案 1 :(得分:5)
如果您使用AFNetworking,为什么不使用UIImageView + AFNetworking类别?只需导入UIImageView + AFNetworking.h并使用此方法:
- (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;
修改:设置图片后,请不要忘记在单元格上调用setNeedsLayout
!
答案 2 :(得分:1)
当您进行异步图像下载时,您无法立即在UITableViewCell
上获取结果图像。因此,您应该按照tableView
indexPath
下载图像并使用下载的图像数组显示它们。
请参阅此link以使用延迟加载下载图片并将其显示在UITableViewCell
。
谢谢!