Abhilasha Thapliyal
Abhilasha Thapliyal

Reputation: 88

Fetching data from url and displaying it in a tableview

In my app i have to fetch images from a json webservice and display them in a table view. While scrolling downwards all the images come correct order but while i revert backwards all the images get over each other. I am using [ tableview reloaddata] then too its happening.

Upvotes: 0

Views: 683

Answers (1)

Karim
Karim

Reputation: 736

This happened to me in my app, where I have a leaderboards table. It is definitely because the tables are being reused.

The easiest way to fix this is simply setting the cell's image to nil first, then downloading and displaying the new image.

There are definitely other ways to do this, but I can definitely vouch for this one, as I use it in my own app, and it works great!!

Here's how I solve the problem.

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString * cellIdentifier = @"Cell";
    UITableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];

    if (!cell)
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];

    // Make sure you set the image for the cell to nil first
    [cell.imageView setImage:nil];

    // Then load your new image using the url and display it
    dispatch_queue_t backgroundQueue = dispatch_queue_create("com.example.imagedownloadqueue", NULL);
    dispatch_async(backgroundQueue, ^(void){
        NSUrl * url = [NSUrl UrlWithString:@"www.example.com"]; // Url of image to download
        UIImage * image = [UIImage imageWithData:[NSData dataWithContentsOfUrl:url]];
        if (image)
        {
            dispatch_async(dispatch_get_main_queue(), ^(void) {
                [cell.imageView setImage:image]; // Display image after it is downloaded
            });
        }
    });

    return cell;
}

Upvotes: 1

Related Questions