读取远程JSON并从URL获取图像

时间:2016-04-19 14:01:34

标签: ios json swift

在我的iOS应用程序中,我尝试读取JSON文件并使用其内容填充表格。下面是JSON文件的示例。

目前,我正在将JSON读入一个名为“items”的可变数组中,然后像这样填充表格单元格。

// Populate the cell
if let showName = self.items[indexPath.row]["Show"] as? NSString {
            cell.textLabel!.text = showName as! String

我希望每个JSON记录的图像也出现在单元格中,这就是我被绊倒的地方。

我有图片的网址,但如何将其放入表格单元格?

我的整个方法可能都是错的,所以我希望被指向正确的方向。

{
        "shows": [{
                "Day": "Sunday",
                "Time": "12am",
                "Show": “Show Name Here",
                "imgPath": "http://remoteserver/image.jpg"
        }, {
                "Day": "Sunday",
                "Time": "1am",
                "Show": "Show Name Here",
                "imgPath": “http://remoteserver/image.jpg"

        }, {
                "Day": "Sunday",
                "Time": "2am",
                "Show": "Show Name Here",
                "imgPath": http://remoteserver/image.jpg"

        }

2 个答案:

答案 0 :(得分:1)

我建议使用像SDWebImage这样的库。这将为您提供将图像异步加载到imageview中的方法,并允许您在下载图像时设置占位符。 您可以从这样的URL设置图像(从SDWebImage文档复制):

[cell.imageView sd_setImageWithURL:[NSURL URLWithString:@"http://www.domain.com/path/to/image.jpg"]
                  placeholderImage:[UIImage imageNamed:@"placeholder.png"]];

此处有更多信息:https://github.com/rs/SDWebImage

答案 1 :(得分:0)

Apple有一个使用RSS的示例项目。 LazyTableImages此代码不是很快,但会准确显示苹果如何处理此问题。

您听到的问题是细胞正在被重复使用,您的图像未被清除或被添加到重复使用的细胞中。