如何将URL中的图像加载到UITableViewCell的UIImageView中?

时间:2017-06-02 04:48:21

标签: objective-c uiimageview

尝试从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

我做错了吗?还有其他最好的方法吗?

3 个答案:

答案 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"]];

You can download class of SDWebImage from this link

相关问题