Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Loading images from a URL into a UITableViewCell's UIImageView

I have the following code: (Note: newsImageURL is an NSArray)

NSString *imagesURL = @"http://aud.edu/images/newsimage01.png,http://aud.edu/images/newsimage04.png,http://aud.edu/images/newsimage02.png,http://aud.edu/images/newsimage03.png,http://aud.edu/images/newsimage01.png,http://aud.edu/images/newsimage04.png,http://aud.edu/images/newsimage01.png,http://aud.edu/images/newsimage04.png,http://aud.edu/images/newsimage01.png,http://aud.edu/images/newsimage04.png,";
newsImageURL = [[NSArray alloc] initWithArray:[AllNewsHeadLine componentsSeparatedByString:@","]];

I am trying to load these images into a cell using the code below:

NSData* imageData = [[NSData alloc] initWithContentsOfURL:[NSURL URLWithString: [newsImageURL objectAtIndex:indexPath.row]]]; 
cell.image = [UIImage imageWithData:imageData];

The image loads fine when I use this line instead:

cell.image = [UIImage imageNamed:@"imagename.png"];

What am I doing wrong?

like image 316
Ahoura Ghotbi Avatar asked Dec 05 '22 19:12

Ahoura Ghotbi


1 Answers

You should use an existing framework which supports caching, default place holders and lazy loading of images.

https://github.com/rs/SDWebImage is a good and simple framework

#import "UIImageView+WebCache.h"

...

- (UITableViewCell *)tableView:(UITableView *)tableView
         cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *MyIdentifier = @"MyIdentifier";

    UITableViewCell *cell =
        [tableView dequeueReusableCellWithIdentifier:MyIdentifier];

    if (cell == nil)
    {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault
                                       reuseIdentifier:MyIdentifier] autorelease];
    }

    // Here we use the new provided setImageWithURL: method to load the web image
    [cell.imageView setImageWithURL:[NSURL URLWithString:@"http://aud.edu/images/newsimage01.png,http://aud.edu/images/newsimage04.png"]
                   placeholderImage:[UIImage imageNamed:@"placeholder.png"]];

    cell.textLabel.text = @"My Text";
    return cell;
}
like image 184
aporat Avatar answered Mar 16 '23 15:03

aporat