Darin
Darin

Reputation: 59

Reading Remote JSON and Getting Image from URL

In my iOS app I am trying to read in a JSON file and populate a table with its contents. Below is a sample of the JSON file.

Presently, I am reading the JSON into a mutable array called “items” and then populating the table cells like this.

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

I would like to have the image for each JSON record appear in the cell as well and that is where I am getting tripped up.

I have the URL to the image but how do I get it into the table cell?

My entire approach may be wrong so I would appreciate being pointed in the right direction.

{
        "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"

        }

Upvotes: 0

Views: 93

Answers (2)

Jaybit
Jaybit

Reputation: 1864

Apple has a example project for this using RSS. LazyTableImages This code is not in swift but will show exactly how apple handled this.

The problem it sounds like you are having is cells are being reused and your image is not being cleared or are being added to a reused cell.

Upvotes: 0

BevTheDev
BevTheDev

Reputation: 583

I'd recommend using a library like SDWebImage for this. That will provide you with methods for loading an image into an imageview asynchronously, and let you set a placeholder while the image is downloading. You can set an image from a url like this (copied from SDWebImage docs):

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

More info here: https://github.com/rs/SDWebImage

Upvotes: 1

Related Questions