如何将URL中的图像加载到UITableViewCell的UIImageView中?
问题描述:
尝试提取从JSON图像和显示器上的tableview细胞,而且在转换到数据变得nill如何将URL中的图像加载到UITableViewCell的UIImageView中?
dispatch_async(dispatch_get_global_queue(0,0), ^{
NSData * data = [[NSData alloc] initWithContentsOfURL: [NSURL URLWithString: @"http://myurl/mypic.jpg"]];
if (data == nil)
return;
dispatch_async(dispatch_get_main_queue(), ^{
// WARNING: is the cell still using the same data by this point??
cell.imageView.image = [UIImage imageWithData: data];
});
});
为NSData的*数据其始终表示零,即使我硬编码等
NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:@"http://upload.wikimedia.org/wikipedia/commons/thumb/6/6b/American_Beaver.jpg/220px-American_Beaver.jpg"]];
它是在数据变量中显示nil
我是否做错了什么?任何其他最好的方式相同?
答
您可以使用SDWebImage为图像执行延迟加载。
#import <SDWebImage/UIImageView+WebCache.h>
[cell.imageView sd_setImageWithURL:[NSURL URLWithString:IMAGE_URL]
placeholderImage:[UIImage imageNamed:@"placeholder.png"]];
答
此代码正在工作,您可能从json得到了错误的图片网址。
dispatch_async(dispatch_get_global_queue(0,0), ^{
NSData * data = [[NSData alloc] initWithContentsOfURL: [NSURL URLWithString: @"http://upload.wikimedia.org/wikipedia/commons/thumb/6/6b/American_Beaver.jpg/220px-American_Beaver.jpg"]];
if (data == nil)
return;
dispatch_async(dispatch_get_main_queue(), ^{
// WARNING: is the cell still using the same data by this point??
UIImage *image = [UIImage imageWithData:data];
NSLog(@"%@",image);
});
});
+0
网址是正确的,只是错误,我把两个差异URL的问题 – sss
+0
此代码不适合你? –
答
#import "SDWebImage/UIImageView+WebCache.h"
[cell.imageView sd_setImageWithURL:[NSURL URLWithString:@"http://www.freeiconspng.com/uploads/flower-png-22.png"]
placeholderImage:[UIImage imageNamed:@"placeholder.png"]];
你尝试这个网址http://upload.wikimedia.org/wikipedia/commons/thumb/6/6b/American_Beaver.jpg/220px-American_Beaver.jpg? –