尝试从JSON获取图像并在tableview单元格上显示但在转换为数据时它变为nill
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我做错了吗?还有其他最好的方法吗?
答案 0 :(得分:1)
您可以使用SDWebImage为图片执行延迟加载。
#import <SDWebImage/UIImageView+WebCache.h>
[cell.imageView sd_setImageWithURL:[NSURL URLWithString:IMAGE_URL]
placeholderImage:[UIImage imageNamed:@"placeholder.png"]];
答案 1 :(得分:0)
此代码正常运行,您可能会从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);
});
});
答案 2 :(得分: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"]];