Related
Shortly, I have an NSDictionary with urls for images that I need to show in my UITableView. Each cell has a title and an image. I had successfully made this happen, although the scrolling was lagging, as it seemed like the cells downloaded their image every time they came into the screen.
I searched for a bit, and found SDWebImage on github. This made the scroll-lagg go away. I am not completely sure what it did, but I believed it did some caching.
But! Every time I open the app for the first time, I see NO images, and I have to scroll down, and back up for them to arrive. And if I exit the app with home-button, and open again, then it seemes like the caching is working, because the images on the screen are visible, however, if I scroll one cell down, then the next cell has no image. Until i scroll past it and back up, or if I click on it. Is this how caching is supposed to work? Or what is the best way to cache images downloaded from the web? The images are being updated rarily, so I was close to just import them to the project, but I like to have the possibility to update images without uploading an update..
Is it impossible to load all the images for the whole tableview form the cache(given that there is something in the cache) at launch? Is that why I sometimes see cells without images?
And yes, I'm having a hard time understanding what cache is.
--EDIT--
I tried this with only images of the same size (500x150), and the aspect-error is gone, however when I scroll up or down, there are images on all cells, but at first they are wrong. After the cell has been in the view for some milliseconds, the right image appears. This is amazingly annoying, but maybe how it has to be?.. It seemes like it chooses the wrong index from the cache at first. If I scroll slow, then I can see the images blink from wrong image to the correct one. If I scroll fast, then I believe the wrong images are visible at all times, but I can't tell due to the fast scrolling. When the fast scrolling slows down and eventually stops, the wrong images still appear, but immediately after it stops scrolling, it updates to the right images. I also have a custom UITableViewCell class, but I haven't made any big changes.. I haven't gone through my code very much yet, but I can't think of what may be wrong.. Maybe I have something in the wrong order.. I have programmed much in java, c#, php etc, but I'm having a hard time understanding Objective-c, with all the .h and .m ...
I have also `
#interface FirstViewController : UITableViewController{
/**/
NSCache *_imageCache;
}
(among other variables) in FirstViewController.h. Is this not correct?
Here's my cellForRowAtIndexPath.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"hallo";
CustomCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil)
{
cell = [[CustomCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
NSMutableArray *marr = [hallo objectAtIndex:indexPath.section];
NSDictionary *dict = [marr objectAtIndex:indexPath.row];
NSString* imageName = [dict objectForKey:#"Image"];
//NSLog(#"url: %#", imageURL);
UIImage *image = [_imageCache objectForKey:imageName];
if(image)
{
cell.imageView.image = image;
}
else
{
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
NSString* imageURLString = [NSString stringWithFormat:#"example.com/%#", imageName];
NSURL *imageURL = [NSURL URLWithString:imageURLString];
UIImage *image = [[UIImage alloc] initWithData:[NSData dataWithContentsOfURL:imageURL]];
if(image)
{
dispatch_async(dispatch_get_main_queue(), ^{
CustomCell *cell =(CustomCell*)[self.tableView cellForRowAtIndexPath:indexPath];
if(cell)
{
cell.imageView.image = image;
}
});
[_imageCache setObject:image forKey:imageName];
}
});
}
cell.textLabel.text = [dict objectForKey:#"Name"];
return cell;
}
Caching just means keeping a copy of the data that you need so that you don't have to load it from some slower source. For example, microprocessors often have cache memory where they keep copies of data so that they don't have to access RAM, which is a lot slower. Hard disks often have memory caches from which the file system can get much quicker access to blocks of data that have been accessed recently.
Similarly, if your app loads a lot of images from the network, it may be in your interest to cache them on your device instead of downloading them every time you need them. There are lots of ways to do that -- it sounds like you already found one. You might want to store the images you download in your app's /Library/Caches directory, especially if you don't expect them to change. Loading the images from secondary storage will be much, much quicker than loading them over the network.
You might also be interested in the little-known NSCache class for keeping the images you need in memory. NSCache works like a dictionary, but when memory gets tight it'll start releasing some of its contents. You can check the cache for a given image first, and if you don't find it there you can then look in your caches directory, and if you don't find it there you can download it. None of this will speed up image loading on your app the first time you run it, but once your app has downloaded most of what it needs it'll be much more responsive.
I think Caleb answered the caching question well. I was just going to touch upon the process for updating your UI as you retrieve images, e.g. assuming you have a NSCache for your images called _imageCache:
First, define an operation queue property for the tableview:
#property (nonatomic, strong) NSOperationQueue *queue;
Then in viewDidLoad, initialize this:
self.queue = [[NSOperationQueue alloc] init];
self.queue.maxConcurrentOperationCount = 4;
And then in cellForRowAtIndexPath, you could then:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"ilvcCell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
// set the various cell properties
// now update the cell image
NSString *imagename = [self imageFilename:indexPath]; // the name of the image being retrieved
UIImage *image = [_imageCache objectForKey:imagename];
if (image)
{
// if we have an cachedImage sitting in memory already, then use it
cell.imageView.image = image;
}
else
{
cell.imageView.image = [UIImage imageNamed:#"blank_cell_image.png"];
// the get the image in the background
[self.queue addOperationWithBlock:^{
// get the UIImage
UIImage *image = [self getImage:imagename];
// if we found it, then update UI
if (image)
{
[[NSOperationQueue mainQueue] addOperationWithBlock:^{
// if the cell is visible, then set the image
UITableViewCell *cell = [self.tableView cellForRowAtIndexPath:indexPath];
if (cell)
cell.imageView.image = image;
}];
[_imageCache setObject:image forKey:imagename];
}
}];
}
return cell;
}
I only mention this as I've seen a few code samples floating around on SO recently that use GCD to update the appropriate UIImageView image property, but in the process of dispatching the UI update back to the main queue, they employ curious techniques (e.g., reloading the cell or table, just updating the image property of the existing cell object returned at the top of the tableView:cellForRowAtIndexPath (which is a problem if the row has scrolled off the screen and the cell has been dequeued and is being reused for a new row), etc.). By using cellForRowAtIndexPath (not to be confused with tableView:cellForRowAtIndexPath), you can determine if the cell is still visible and/or if it may have scrolled off and been dequeued and reused.
The simplest solution is to go with something heavily used that has been stress tested.
SDWebImage is a powerful tool that helped me solve a similar problem and can easily be installed w/ cocoa pods. In podfile:
platform :ios, '6.1'
pod 'SDWebImage', '~>3.6'
Setup cache:
SDImageCache *imageCache = [[SDImageCache alloc] initWithNamespace:#"myNamespace"];
[imageCache queryDiskCacheForKey:myCacheKey done:^(UIImage *image)
{
// image is not nil if image was found
}];
Cache image:
[[SDImageCache sharedImageCache] storeImage:myImage forKey:myCacheKey];
https://github.com/rs/SDWebImage
I think will be better for you user something like DLImageLoader.
More info -> https://github.com/AndreyLunevich/DLImageLoader-iOS
[[DLImageLoader sharedInstance] loadImageFromUrl:#"image_url_here"
completed:^(NSError *error, UIImage *image) {
if (error == nil) {
imageView.image = image;
} else {
// if we got an error when load an image
}
}];
For the part of the question about wrong images, it's because of the reuse of cells. Reuse of cells means that the existing cells, which go out of view (for example, the cells which go out of the screen in the top when you scroll towards the bottom are the ones coming back again from the bottom.) And so you get incorrect images. But once the cell shows up, the code for fetching the proper image executes and you get the proper images.
You can use a placeholder in 'prepareForReuse' method of the cell. This function is mostly used when you need to reset the values when the cell is brought up for reuse. Setting a placeholder here will make sure you won't get any incorrect images.
Caching images can be done as simply as this.
ImageService.m
#implementation ImageService{
NSCache * Cache;
}
const NSString * imageCacheKeyPrefix = #"Image-";
-(id) init {
self = [super init];
if(self) {
Cache = [[NSCache alloc] init];
}
return self;
}
/**
* Get Image from cache first and if not then get from server
*
**/
- (void) getImage: (NSString *) key
imagePath: (NSString *) imagePath
completion: (void (^)(UIImage * image)) handler
{
UIImage * image = [Cache objectForKey: key];
if( ! image || imagePath == nil || ! [imagePath length])
{
image = NOIMAGE; // Macro (UIImage*) for no image
[Cache setObject:image forKey: key];
dispatch_async(dispatch_get_main_queue(), ^(void){
handler(image);
});
}
else
{
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH,0ul ),^(void){
UIImage * image = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:[imagePath stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]]]];
if( !image)
{
image = NOIMAGE;
}
[Cache setObject:image forKey: key];
dispatch_async(dispatch_get_main_queue(), ^(void){
handler(image);
});
});
}
}
- (void) getUserImage: (NSString *) userId
completion: (void (^)(UIImage * image)) handler
{
[self getImage: [NSString stringWithFormat: #"%#user-%#", imageCacheKeyPrefix, userId]
imagePath: [NSString stringWithFormat: #"http://graph.facebook.com/%#/picture?type=square", userId]
completion: handler];
}
SomeViewController.m
[imageService getUserImage: userId
completion: ^(UIImage *image) {
annotationImage.image = image;
}];
////.h file
#import <UIKit/UIKit.h>
#interface UIImageView (KJ_Imageview_WebCache)
-(void)loadImageUsingUrlString :(NSString *)urlString placeholder :(UIImage *)placeholder_image;
#end
//.m file
#import "UIImageView+KJ_Imageview_WebCache.h"
#implementation UIImageView (KJ_Imageview_WebCache)
-(void)loadImageUsingUrlString :(NSString *)urlString placeholder :(UIImage *)placeholder_image
{
NSString *imageUrlString = urlString;
NSURL *url = [NSURL URLWithString:urlString];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *getImagePath = [documentsDirectory stringByAppendingPathComponent:[self tream_char:urlString]];
NSLog(#"getImagePath--->%#",getImagePath);
UIImage *customImage = [UIImage imageWithContentsOfFile:getImagePath];
if (customImage)
{
self.image = customImage;
return;
}
else
{
self.image=placeholder_image;
}
NSURLSession *session = [NSURLSession sharedSession];
NSURLSessionDataTask *uploadTask = [session dataTaskWithURL:url completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
if (error)
{
NSLog(#"%#",[error localizedDescription]);
self.image=placeholder_image;
return ;
}
dispatch_async(dispatch_get_main_queue(), ^{
UIImage *imageToCache = [UIImage imageWithData:data];
if (imageUrlString == urlString)
{
self.image = imageToCache;
}
[self saveImage:data ImageString:[self tream_char:urlString]];
});
}];
[uploadTask resume];
}
-(NSString *)tream_char :(NSString *)string
{
NSString *unfilteredString =string;
NSCharacterSet *notAllowedChars = [[NSCharacterSet characterSetWithCharactersInString:#"!##$%^&*()_+|abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890"] invertedSet];
NSString *resultString = [[unfilteredString componentsSeparatedByCharactersInSet:notAllowedChars] componentsJoinedByString:#""];
NSLog (#"Result: %#", resultString);
return resultString;
}
-(void)saveImage : (NSData *)Imagedata ImageString : (NSString *)imageString
{
NSArray* documentDirectories = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask,YES);
NSString* documentDirectory = [documentDirectories objectAtIndex:0];
NSString* documentDirectoryFilename = [documentDirectory stringByAppendingPathComponent:imageString];
if (![Imagedata writeToFile:documentDirectoryFilename atomically:NO])
{
NSLog((#"Failed to cache image data to disk"));
}
else
{
NSLog(#"the cachedImagedPath is %#",documentDirectoryFilename);
}
}
#end
/// call
[cell.ProductImage loadImageUsingUrlString:[[ArrProductList objectAtIndex:indexPath.row] valueForKey:#"product_image"] placeholder:[UIImage imageNamed:#"app_placeholder"]];
This question already has answers here:
GCD UITableView asynchronous load images, wrong cells are loaded until new image download
(3 answers)
Closed 7 years ago.
I have a table view with custom cells. Every cell has an image, title, and a description. When I first load the table, it loads fine. if I slowly scroll trough the images, also seems to work fine. As soon as I scroll down fast (assuming the number of cells is large enough to not fit in without scrolling up and down) the images start to changes cells in a random order. Some cells have the same image twice.
Any clue why this is happening?
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
BookmarkCellViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
NewsArticle *currArt = [self.lN_Dept objectAtIndex:indexPath.row];
if(currArt.artImage == Nil)
{
if([currArt.mainImage_URL rangeOfString:#"<img src="].location != NSNotFound)
{
NSRange range = [currArt.mainImage_URL rangeOfString:#"<img src=\"/CONC/"];
NSString *substring = [[currArt.mainImage_URL substringFromIndex:NSMaxRange(range)] stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
NSRange range2 = [substring rangeOfString:#"\""];
NSString *substring2 = [[substring substringToIndex:NSMaxRange(range2)-1] stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
NSString *imageURL = [PUB_URL stringByAppendingString:substring2];
[self downloadImageWithURL:[NSURL URLWithString:imageURL] completionBlock:^(BOOL succeeded, UIImage *image) {
if (succeeded) {
currArt.artImage = image;
cell.ArtDisplayImage.image = currArt.artImage;
}
}];
}
}
else
{
cell.ArtDisplayImage.image = currArt.artImage;
}
[cell configureCellForEntry:currArticle];
return cell;
}
- (void)downloadImageWithURL:(NSURL *)url completionBlock:(void (^)(BOOL succeeded, UIImage *image))completionBlock
{
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[NSURLConnection sendAsynchronousRequest:request
queue:[NSOperationQueue mainQueue]
completionHandler:^(NSURLResponse *response, NSData *Data, NSError *error) {
if ( !error )
{
UIImage *image = [[UIImage alloc] initWithData:Data];
completionBlock(YES,image);
} else{
completionBlock(NO,nil);
}
}];
}
It happens because you misunderstand how UITableView works. Let's imagine your table view has 100 cells and it can display 10 cells simultaneously. When table view loads, it creates 10 instances of your cells. When you start scrolling down through the table view it actually doesn't creates new instances of your cells – it reuses cells that have disappeared from the screen (because you are calling [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];). That means that the cell at index 10 will have the same reference that the cell at index 0.
Back to your question you are loading images with
[self downloadImageWithURL:[NSURL URLWithString:imageURL] completionBlock:^(BOOL succeeded, UIImage *image) {
if (succeeded) {
currArt.artImage = image;
cell.ArtDisplayImage.image = currArt.artImage;
}
}];
In case the image was downloaded faster then the cell was reused (which happens when your are scrolling slowly) everything will be alright. But in case cell was reused before image was downloaded then there are two blocks in memory that are downloading images for that cell. To solve this issue I would recommend you to use SDWebImage which handles this situations automatically or cancel downloading of images for cells which are disappeared from the screen. Hope this will help.
There's probably a race condition here. A download is queued up for a given cell and then that cell is reused and another image is set or download is queued but then the first download completes and sets the image even though the cell represents a different element now. If you want to see if this is indeed the issue, disable cell reuse (instantiate a new cell for every row). If the problem goes away, then that was it.
One thing you can do is cancel an existing download that was started by a given cell if that cell is reused. Check out the open source library SDWebImage which handles this issue this way.
Another thing you can do is have the cell store the URL it is currently trying to load and compare the URL of the resulting download against the cell's stored URL to see if they are still the same (and only set the image if they are still the same).
Something like this should do it:
if(currArt.artImage == Nil)
{
if([currArt.mainImage_URL rangeOfString:#"<img src="].location != NSNotFound)
{
NSRange range = [currArt.mainImage_URL rangeOfString:#"<img src=\"/CONC/"];
NSString *substring = [[currArt.mainImage_URL substringFromIndex:NSMaxRange(range)] stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
NSRange range2 = [substring rangeOfString:#"\""];
NSString *substring2 = [[substring substringToIndex:NSMaxRange(range2)-1] stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
NSString *imageURL = [PUB_URL stringByAppendingString:substring2];
cell.imageURL = imageURL; // you need to add an imageURL string property to your cells
// you need to return the URL string in your block to compare it
[self downloadImageWithURL:[NSURL URLWithString:imageURL] completionBlock:^(BOOL succeeded, UIImage *image, NSString *url)
{
if (succeeded)
{
currArt.artImage = image;
if(cell.imageURL isEqualToString:url])
{
cell.ArtDisplayImage.image = currArt.artImage;
}
}
}];
}
}
else
{
cell.ArtDisplayImage.image = currArt.artImage;
cell.imageURL = nil; // make sure it is not overwritten
}
So something like this:
[self downloadImageWithURL:[NSURL URLWithString:imageURL] completionBlock:^(BOOL succeeded, UIImage *image) {
if (succeeded) {
YourCellType *cellToUpdate = [tableView cellForIndexPath:indexPath];
if (cellToUpdate)
{
currArt.artImage = image;
cellToUpdate.ArtDisplayImage.image = currArt.artImage;
}
}
}];
I hava a uitableview , with custom cell containing two UImages. The logo images are taken from an online website, that's why there's a need to cache the images. Loading the image till now is made like this :
NSURL * imageURL = [NSURL URLWithString:[arra1 objectAtIndex:indexPath.row / 2]];
NSData * imageData = [NSData dataWithContentsOfURL:imageURL];
NSURL * imageURL2 = [NSURL URLWithString:[arra2 objectAtIndex:indexPath.row / 2]];
NSData * imageData2 = [NSData dataWithContentsOfURL:imageURL2];
cell.ima1.image = [UIImage imageWithData:imageData];
cell.ima2.image2 = [UIImage imageWithData:imageData2];
What i learned from searching , is that dataWithContentsOfURL is not asynchronous , and while scrolling it will take a lot of time. I tried several methods but i can't seem to get to right one. This is my first time caching UIImages , i would highly appreciate a detailed explanation with implementation so i could learn aside from getting the job done.
Many Thanks
I use this Library which is just perfect
SDWebImage
You just need to #import <SDWebImage/UIImageView+WebCache.h> to your project, and you can define also the placeholder when image is being downloaded with just this code:
- (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://www.domain.com/path/to/image.jpg"]
placeholderImage:[UIImage imageNamed:#"placeholder.png"]];
cell.textLabel.text = #"My Text";
return cell;
}
It also cache downloaded images and gives you great performance.
Hope it will help you!
SDWebImage, in my opinion, is the best option.
You simply include it in your app and use it like this:
SDWebImageManager *manager = [SDWebImageManager sharedManager];
[manager downloadWithURL:[NSURL URLWithString:image_url]
options:0
progress:nil
completed:^(UIImage *images, NSError *error, SDImageCacheType cacheType, BOOL complete) {
myImageView.image = images;
}] ;
It download images asynchronously, so it does not block UI.
You can check these sample application
LazyTableImages - Sample application from Apple
MonoTouch-LazyTableImages
robertmryan- LazyTableImages - Explains clearly the limitations from apple's sample application.
Hope this helps.
Checkout UIImageLoader https://github.com/gngrwzrd/UIImageLoader
Easy to load an image, and you get callbacks for all the scenarios you would want to handle:
NSURL * imageURL = myURL;
[[UIImageLoader defaultLoader] loadImageWithURL:imageURL \
hasCache:^(UIImage *image, UIImageLoadSource loadedFromSource) {
//there was a cached image available. use that.
self.imageView.image = image;
} sendRequest:^(BOOL didHaveCachedImage) {
//a request is being made for the image.
if(!didHaveCachedImage) {
//there was not a cached image available, set a placeholder or do nothing.
self.loader.hidden = FALSE;
[self.loader startAnimating];
self.imageView.image = [UIImage imageNamed:#"placeholder"];
}
} requestCompleted:^(NSError *error, UIImage *image, UIImageLoadSource loadedFromSource) {
//network request finished.
[self.loader stopAnimating];
self.loader.hidden = TRUE;
if(loadedFromSource == UIImageLoadSourceNetworkToDisk) {
//the image was downloaded and saved to disk.
//since it was downloaded it has been updated since
//last cached version, or is brand new
self.imageView.image = image;
}
}];
I am a bit desperated about my sectioned tableview. I use a custom UITableViewCell with 4 images like the one below:
I try to load the images via SDWebImage for each cell.
The loading procedures are all done in my custom UITableViewCell - not in the UITableViewController. From the cellForRowAtIndexPath i just call [cell setup] which executes the following code in the current cell:
NSArray *imageViews = [NSArray arrayWithObjects:self.imageView1, self.imageView2, self.imageView3, self.imageView4, nil];
for (int i = 0; i < self.products.count; i++) {
Product *currentProduct = [self.products objectAtIndex:i];
UIImageView *currentImageView = [imageViews objectAtIndex:i];
NSString *thumbURL = [[CommonCode getUnzippedDirectory] stringByAppendingPathComponent:currentProduct.collectionFolderName];
thumbURL = [thumbURL stringByAppendingPathComponent:thumbFolder];
thumbURL = [thumbURL stringByAppendingPathComponent:currentProduct.product_photo];
[currentImageView setContentMode:UIViewContentModeScaleAspectFit];
[currentImageView setImageWithURL:[NSURL fileURLWithPath:thumbURL]
placeholderImage:[UIImage imageNamed:#"placeholder.png"]];
}
The images are all stored in the documents directory and are not greater than max. 500Kb.
Problem:
My Problem is that when I scroll through my tableview it suddenly crashes and I don't know why. Enabling a symbolic breakpoint for all exceptions shows that it crashes because of one line in SDWebImage. Unfortunately there isn't a debugger output: (It crashes where the image is allocated)
UIImage *image = nil;
if ([imageOrData isKindOfClass:[NSData class]])
{
image = [[UIImage alloc] initWithData:(NSData *)imageOrData];
}
I also tried to load images via dispatch_asnyc with a similar result. Is it possible that it has something to do with concurrent file operations?
Additionally I get Memory Warnings when I scroll very fast so that I have to clear the cache of SDWebImage. At the same time it stops at the code line in SDWebImage mentioned above.
I already searched the web for 2 days now and I didn't find something useful. I would be glad for some hints to fix this problem. If somebody needs additional data such as crash reports or something, just let me know and I will provide them quickly.
I have meet the same problem, But I solve it like below temporarily, but it cause memory problem especially on iPhone 4s
NSArray *arrImgs = cellModel.thumbnails_qqnews;
if (arrImgs.count > 0) {
[self.imgView.subviews enumerateObjectsUsingBlock:^(__kindof UIImageView * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
[obj sd_setImageWithURL:[NSURL URLWithString:arrImgs[idx]] placeholderImage:[UIImage imageNamed:#"placeholdImage"] completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
if (image != nil) {
obj.image = [UIImage cutImageWithTargetSize:[NEMulTiNewsCell getImgSize] image:image];
}
}];
}];
}
I think multi images download is illogical,but the method i think is download multi images then draw multi images in one image then display, but it may create large number line of code.
Shortly, I have an NSDictionary with urls for images that I need to show in my UITableView. Each cell has a title and an image. I had successfully made this happen, although the scrolling was lagging, as it seemed like the cells downloaded their image every time they came into the screen.
I searched for a bit, and found SDWebImage on github. This made the scroll-lagg go away. I am not completely sure what it did, but I believed it did some caching.
But! Every time I open the app for the first time, I see NO images, and I have to scroll down, and back up for them to arrive. And if I exit the app with home-button, and open again, then it seemes like the caching is working, because the images on the screen are visible, however, if I scroll one cell down, then the next cell has no image. Until i scroll past it and back up, or if I click on it. Is this how caching is supposed to work? Or what is the best way to cache images downloaded from the web? The images are being updated rarily, so I was close to just import them to the project, but I like to have the possibility to update images without uploading an update..
Is it impossible to load all the images for the whole tableview form the cache(given that there is something in the cache) at launch? Is that why I sometimes see cells without images?
And yes, I'm having a hard time understanding what cache is.
--EDIT--
I tried this with only images of the same size (500x150), and the aspect-error is gone, however when I scroll up or down, there are images on all cells, but at first they are wrong. After the cell has been in the view for some milliseconds, the right image appears. This is amazingly annoying, but maybe how it has to be?.. It seemes like it chooses the wrong index from the cache at first. If I scroll slow, then I can see the images blink from wrong image to the correct one. If I scroll fast, then I believe the wrong images are visible at all times, but I can't tell due to the fast scrolling. When the fast scrolling slows down and eventually stops, the wrong images still appear, but immediately after it stops scrolling, it updates to the right images. I also have a custom UITableViewCell class, but I haven't made any big changes.. I haven't gone through my code very much yet, but I can't think of what may be wrong.. Maybe I have something in the wrong order.. I have programmed much in java, c#, php etc, but I'm having a hard time understanding Objective-c, with all the .h and .m ...
I have also `
#interface FirstViewController : UITableViewController{
/**/
NSCache *_imageCache;
}
(among other variables) in FirstViewController.h. Is this not correct?
Here's my cellForRowAtIndexPath.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"hallo";
CustomCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil)
{
cell = [[CustomCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
NSMutableArray *marr = [hallo objectAtIndex:indexPath.section];
NSDictionary *dict = [marr objectAtIndex:indexPath.row];
NSString* imageName = [dict objectForKey:#"Image"];
//NSLog(#"url: %#", imageURL);
UIImage *image = [_imageCache objectForKey:imageName];
if(image)
{
cell.imageView.image = image;
}
else
{
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
NSString* imageURLString = [NSString stringWithFormat:#"example.com/%#", imageName];
NSURL *imageURL = [NSURL URLWithString:imageURLString];
UIImage *image = [[UIImage alloc] initWithData:[NSData dataWithContentsOfURL:imageURL]];
if(image)
{
dispatch_async(dispatch_get_main_queue(), ^{
CustomCell *cell =(CustomCell*)[self.tableView cellForRowAtIndexPath:indexPath];
if(cell)
{
cell.imageView.image = image;
}
});
[_imageCache setObject:image forKey:imageName];
}
});
}
cell.textLabel.text = [dict objectForKey:#"Name"];
return cell;
}
Caching just means keeping a copy of the data that you need so that you don't have to load it from some slower source. For example, microprocessors often have cache memory where they keep copies of data so that they don't have to access RAM, which is a lot slower. Hard disks often have memory caches from which the file system can get much quicker access to blocks of data that have been accessed recently.
Similarly, if your app loads a lot of images from the network, it may be in your interest to cache them on your device instead of downloading them every time you need them. There are lots of ways to do that -- it sounds like you already found one. You might want to store the images you download in your app's /Library/Caches directory, especially if you don't expect them to change. Loading the images from secondary storage will be much, much quicker than loading them over the network.
You might also be interested in the little-known NSCache class for keeping the images you need in memory. NSCache works like a dictionary, but when memory gets tight it'll start releasing some of its contents. You can check the cache for a given image first, and if you don't find it there you can then look in your caches directory, and if you don't find it there you can download it. None of this will speed up image loading on your app the first time you run it, but once your app has downloaded most of what it needs it'll be much more responsive.
I think Caleb answered the caching question well. I was just going to touch upon the process for updating your UI as you retrieve images, e.g. assuming you have a NSCache for your images called _imageCache:
First, define an operation queue property for the tableview:
#property (nonatomic, strong) NSOperationQueue *queue;
Then in viewDidLoad, initialize this:
self.queue = [[NSOperationQueue alloc] init];
self.queue.maxConcurrentOperationCount = 4;
And then in cellForRowAtIndexPath, you could then:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"ilvcCell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
// set the various cell properties
// now update the cell image
NSString *imagename = [self imageFilename:indexPath]; // the name of the image being retrieved
UIImage *image = [_imageCache objectForKey:imagename];
if (image)
{
// if we have an cachedImage sitting in memory already, then use it
cell.imageView.image = image;
}
else
{
cell.imageView.image = [UIImage imageNamed:#"blank_cell_image.png"];
// the get the image in the background
[self.queue addOperationWithBlock:^{
// get the UIImage
UIImage *image = [self getImage:imagename];
// if we found it, then update UI
if (image)
{
[[NSOperationQueue mainQueue] addOperationWithBlock:^{
// if the cell is visible, then set the image
UITableViewCell *cell = [self.tableView cellForRowAtIndexPath:indexPath];
if (cell)
cell.imageView.image = image;
}];
[_imageCache setObject:image forKey:imagename];
}
}];
}
return cell;
}
I only mention this as I've seen a few code samples floating around on SO recently that use GCD to update the appropriate UIImageView image property, but in the process of dispatching the UI update back to the main queue, they employ curious techniques (e.g., reloading the cell or table, just updating the image property of the existing cell object returned at the top of the tableView:cellForRowAtIndexPath (which is a problem if the row has scrolled off the screen and the cell has been dequeued and is being reused for a new row), etc.). By using cellForRowAtIndexPath (not to be confused with tableView:cellForRowAtIndexPath), you can determine if the cell is still visible and/or if it may have scrolled off and been dequeued and reused.
The simplest solution is to go with something heavily used that has been stress tested.
SDWebImage is a powerful tool that helped me solve a similar problem and can easily be installed w/ cocoa pods. In podfile:
platform :ios, '6.1'
pod 'SDWebImage', '~>3.6'
Setup cache:
SDImageCache *imageCache = [[SDImageCache alloc] initWithNamespace:#"myNamespace"];
[imageCache queryDiskCacheForKey:myCacheKey done:^(UIImage *image)
{
// image is not nil if image was found
}];
Cache image:
[[SDImageCache sharedImageCache] storeImage:myImage forKey:myCacheKey];
https://github.com/rs/SDWebImage
I think will be better for you user something like DLImageLoader.
More info -> https://github.com/AndreyLunevich/DLImageLoader-iOS
[[DLImageLoader sharedInstance] loadImageFromUrl:#"image_url_here"
completed:^(NSError *error, UIImage *image) {
if (error == nil) {
imageView.image = image;
} else {
// if we got an error when load an image
}
}];
For the part of the question about wrong images, it's because of the reuse of cells. Reuse of cells means that the existing cells, which go out of view (for example, the cells which go out of the screen in the top when you scroll towards the bottom are the ones coming back again from the bottom.) And so you get incorrect images. But once the cell shows up, the code for fetching the proper image executes and you get the proper images.
You can use a placeholder in 'prepareForReuse' method of the cell. This function is mostly used when you need to reset the values when the cell is brought up for reuse. Setting a placeholder here will make sure you won't get any incorrect images.
Caching images can be done as simply as this.
ImageService.m
#implementation ImageService{
NSCache * Cache;
}
const NSString * imageCacheKeyPrefix = #"Image-";
-(id) init {
self = [super init];
if(self) {
Cache = [[NSCache alloc] init];
}
return self;
}
/**
* Get Image from cache first and if not then get from server
*
**/
- (void) getImage: (NSString *) key
imagePath: (NSString *) imagePath
completion: (void (^)(UIImage * image)) handler
{
UIImage * image = [Cache objectForKey: key];
if( ! image || imagePath == nil || ! [imagePath length])
{
image = NOIMAGE; // Macro (UIImage*) for no image
[Cache setObject:image forKey: key];
dispatch_async(dispatch_get_main_queue(), ^(void){
handler(image);
});
}
else
{
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH,0ul ),^(void){
UIImage * image = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:[imagePath stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]]]];
if( !image)
{
image = NOIMAGE;
}
[Cache setObject:image forKey: key];
dispatch_async(dispatch_get_main_queue(), ^(void){
handler(image);
});
});
}
}
- (void) getUserImage: (NSString *) userId
completion: (void (^)(UIImage * image)) handler
{
[self getImage: [NSString stringWithFormat: #"%#user-%#", imageCacheKeyPrefix, userId]
imagePath: [NSString stringWithFormat: #"http://graph.facebook.com/%#/picture?type=square", userId]
completion: handler];
}
SomeViewController.m
[imageService getUserImage: userId
completion: ^(UIImage *image) {
annotationImage.image = image;
}];
////.h file
#import <UIKit/UIKit.h>
#interface UIImageView (KJ_Imageview_WebCache)
-(void)loadImageUsingUrlString :(NSString *)urlString placeholder :(UIImage *)placeholder_image;
#end
//.m file
#import "UIImageView+KJ_Imageview_WebCache.h"
#implementation UIImageView (KJ_Imageview_WebCache)
-(void)loadImageUsingUrlString :(NSString *)urlString placeholder :(UIImage *)placeholder_image
{
NSString *imageUrlString = urlString;
NSURL *url = [NSURL URLWithString:urlString];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *getImagePath = [documentsDirectory stringByAppendingPathComponent:[self tream_char:urlString]];
NSLog(#"getImagePath--->%#",getImagePath);
UIImage *customImage = [UIImage imageWithContentsOfFile:getImagePath];
if (customImage)
{
self.image = customImage;
return;
}
else
{
self.image=placeholder_image;
}
NSURLSession *session = [NSURLSession sharedSession];
NSURLSessionDataTask *uploadTask = [session dataTaskWithURL:url completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
if (error)
{
NSLog(#"%#",[error localizedDescription]);
self.image=placeholder_image;
return ;
}
dispatch_async(dispatch_get_main_queue(), ^{
UIImage *imageToCache = [UIImage imageWithData:data];
if (imageUrlString == urlString)
{
self.image = imageToCache;
}
[self saveImage:data ImageString:[self tream_char:urlString]];
});
}];
[uploadTask resume];
}
-(NSString *)tream_char :(NSString *)string
{
NSString *unfilteredString =string;
NSCharacterSet *notAllowedChars = [[NSCharacterSet characterSetWithCharactersInString:#"!##$%^&*()_+|abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890"] invertedSet];
NSString *resultString = [[unfilteredString componentsSeparatedByCharactersInSet:notAllowedChars] componentsJoinedByString:#""];
NSLog (#"Result: %#", resultString);
return resultString;
}
-(void)saveImage : (NSData *)Imagedata ImageString : (NSString *)imageString
{
NSArray* documentDirectories = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask,YES);
NSString* documentDirectory = [documentDirectories objectAtIndex:0];
NSString* documentDirectoryFilename = [documentDirectory stringByAppendingPathComponent:imageString];
if (![Imagedata writeToFile:documentDirectoryFilename atomically:NO])
{
NSLog((#"Failed to cache image data to disk"));
}
else
{
NSLog(#"the cachedImagedPath is %#",documentDirectoryFilename);
}
}
#end
/// call
[cell.ProductImage loadImageUsingUrlString:[[ArrProductList objectAtIndex:indexPath.row] valueForKey:#"product_image"] placeholder:[UIImage imageNamed:#"app_placeholder"]];