Related
I am using following code to fetch images and AVAsset from PHAsset. Here are two arrays in code :
galleryArr : to store images for collection view.
mutableDataArr : store images (for image asset) and videos (for AVAsset) to upload on server
Its very slow to fetch all images from PHAssets array.
I googled about this, most of people says remove this line [options setSynchronous:YES]; but if I remove this line then completion is called twice and array duplicates the objects (as objects are appended in array within completion).
for (int i = 0; i < assets.count; i++) {
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
PHImageRequestOptions *options = [[PHImageRequestOptions alloc] init];
options.deliveryMode = PHImageRequestOptionsDeliveryModeOpportunistic;
options.resizeMode = PHImageRequestOptionsResizeModeExact;
[options setNetworkAccessAllowed:YES];
[options setSynchronous:YES];
PHImageManager *manager = PHImageManager.defaultManager;
PHVideoRequestOptions *videoOptions = [[PHVideoRequestOptions alloc] init];
videoOptions.networkAccessAllowed = YES;
__weak typeof(self) weakSelf = self;
if (assets[i].mediaType == PHAssetMediaTypeVideo) {
[manager requestAVAssetForVideo:[assets objectAtIndex:i] options:videoOptions resultHandler:^(AVAsset * _Nullable asset, AVAudioMix * _Nullable audioMix, NSDictionary * _Nullable info) {
if ([asset isKindOfClass:[AVURLAsset class]])
{
[weakSelf.mutableDataArr addObject:asset];
}
}];
}
[manager requestImageForAsset:[assets objectAtIndex:i]
targetSize: CGSizeMake(1024, 1024) //PHImageManagerMaximumSize
contentMode:PHImageContentModeAspectFit
options:options
resultHandler:^(UIImage *image, NSDictionary *info) {
if (image) {
dispatch_async(dispatch_get_main_queue(), ^{
if (assets[i].mediaType != PHAssetMediaTypeVideo) {
[weakSelf.mutableDataArr addObject:image];
}
[galleryArr addObject:image];
if (i+1 == assets.count) {
[SVProgressHUD dismiss];
[weakSelf.galleryCollectionView reloadData];
}
});
}
}];
});
}
Any suggestion please?
Just one thought, it looks like you are loading all the images from the array before removing your progress HUD and displaying the gallery. As the number of images could be very large and presuming you are using a collection view or similar, that's quite an overhead before anything is displayed.
I did something like this a while ago and instead of looping through the array and loading everything up front, I let the cells request images as they needed them. This makes it very fast and efficient as cells can display immediately with a loading icon, then flip to the image when it was available. Efficiency comes from only loading images the user is actually going to see.
To make things performant, and by performant I mean I could scroll as fast as I liked without the display freezing, each cell would first check an in memory cache for the image, then trigger a request for an image on a background thread.
When the image was returned, the cell would add it to the in memory cache and then if the cell had not being reused for a different image (due to fast scrolling) it would display the image.
Further, I also used a NSCache for the in memory cache so that if the app started to use a lot of memory, images would be automatically dropped and reloaded the next time a cell wanted one.
The summary is to use a memory aware cache, and only load what you actually need.
I am developing an app with a sample UICollectionView that should load a bunch of icons that it downloads from the internet. So basically the server retrieves a list with the URLs of each icon inside a JSON file, the app parses it, and then each cell downloads the corresponding image.
The problem with this approach seems to be that if the user starts scrolling while the images are downloading, the user will start seeing the images in the wrong order! It's like UICollectionView is trying to 'help me' and it renders the content it's got in the wrong place!
I've seen many threads about this, I tried out most of their suggestions but with out much luck so far. Anybody seen something like this?
This is how the cellForItemAtIndexPath looks like:
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
PeqImage *image = [self.responseIcons objectAtIndex:indexPath.row];
PeqCustomCell *cell = [self.collectionView dequeueReusableCellWithReuseIdentifier:#"PeqCustomCell" forIndexPath:indexPath];
cell.peqImage = image;
cell.imageName = [NSString stringWithFormat:#"%#.png",image.assetId];
NSString *theImageUrl = [NSString stringWithFormat:#"http://www.XXXX.com/pb/images/uncompressed/%ld.png",(long)indexPath.row];
[cell downloadImage:[NSURL URLWithString:theImageUrl]];
return cell;
}
And this is how the download algorithm looks like (using UIImageView+AFNetworking):
- (void) downloadImageWithUrl:(NSURL*) url completion:(PeqCustomCellCompletionBlock)completionBlock
{UIImage *placeholder = [UIImage imageNamed:#"placeholder"];
NSURLRequest *jpegURLRequest = [NSURLRequest requestWithURL:url];
self.imageUrl = url.absoluteString;
[self.imageView setImageWithURLRequest:jpegURLRequest
placeholderImage:placeholder
success:^(NSURLRequest *request, NSHTTPURLResponse * _Nullable response, UIImage *image) {
image = [self normalizeImage:image];
completionBlock(image);
}
failure:^(NSURLRequest * _Nonnull request, NSHTTPURLResponse * _Nullable response, NSError * _Nonnull error) {
NSLog(#"Error downloading image from network");
}];
}
You should use SDWebImage library to handle this kind of stuff something like,
#import <SDWebImage/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 sd_setImageWithURL: method to load the web image
[cell.imageView sd_setImageWithURL:[NSURL URLWithString:#"http://www.domain.com/path/to/image.jpg"]
placeholderImage:[UIImage imageNamed:#"placeholder.png"]];
cell.textLabel.text = #"My Text";
return cell;
}
here is the example of tableview you can use same for your collection view!!
this library cache the images for reusability.
If you want to implement or know native way of this stuff then you can refer Loading Images in UICollectionViewCell: Naive to the Clever.
I suspect threads as being the culprit. All UI code must be called from the main thread. These days with so many blocks in use, it's easy to accidentally make UI calls from a background thread. When you do this, all manner of weirdness begins to materialize.
I'd try changing your last snippet of code to this, so that the image calls get dispatched on the main thread. I've just added a dispatch_async() function.
self.imageUrl = url.absoluteString;
[self.imageView setImageWithURLRequest:jpegURLRequest
placeholderImage:placeholder
success:^(NSURLRequest *request, NSHTTPURLResponse * _Nullable response, UIImage *image){
dispatch_async(dispatch_get_main_queue(), ^{
image = [self normalizeImage:image];
completionBlock(image);
});
}
failure:^(NSURLRequest * _Nonnull request, NSHTTPURLResponse * _Nullable response, NSError * _Nonnull error) {
NSLog(#"Error downloading image from network");
}];
The problem is that collection view cells are reused. So you're' telling a cell to download a particular image while its onscreen, and then it goes offscreen and gets reused when the collection view needs another cell, and then you're telling the SAME cell to download another image. Whichever image finishes downloading last is the last one that will be displayed.
In your download completion block, before setting image = [self normalizeImage:image];, you should check if the request url matches the current self.imageUrl. If it doesn't, then the image is from an old request and you don't want to display it in the cell.
The issue is that you re-download the image every time the cell is hidden and shown again. The better method is to download all the data in advance and then populate the collectionView using that.
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"]];
Anyway to handle or display UIImage with caching and with placeholder?
I have found one answer from stack exchange but it didnot work for me given below the link :
Best way to cache images on ios app?
Notes: I dont have any URL because i get image object of PHIMAGE asset library.
You can use SDWebImage
It is very simple to display and cache image.
[imageView sd_setImageWithURL:[NSURL URLWithString:#"http://www.image_url.com"]
placeholderImage:[UIImage imageNamed:#"placeholder.png"]];
You can use a very usefull library called SDWebImage
SDWebImage automagically cache all your images when you provide a valid URL with the sd_setImageWithURL. So the next time you call it, will use the cache system instead of re-download the image.
Example to implement in a UIImageView from their github:
// Here we use the new provided sd_setImageWithURL: method to load the web image
[cell.imageView sd_setImageWithURL:[NSURL URLWithString:#"http://www.domain.com/path/to/image.jpg"]
placeholderImage:[UIImage imageNamed:#"placeholder.png"]];
There was a problem of smoothing an all image while scroll the table but there is an issue of reload the cell not the caching problem i solved this issue.
I get an image one by one from local identifier which is provided by PHAsset framework and display that image into cell.
For reference Code:
PHFetchResult *savedAssets = [PHAsset fetchAssetsWithLocalIdentifiers:#[your local identifier] options:nil];
[savedAssets enumerateObjectsUsingBlock:^(PHAsset *asset, NSUInteger idx, BOOL *stop) {
//this gets called for every asset from its localIdentifier you saved
PHImageRequestOptions * imageRequestOptions = [[PHImageRequestOptions alloc] init];
imageRequestOptions.synchronous = YES;
imageRequestOptions.deliveryMode = PHImageRequestOptionsResizeModeFast;
[[PHImageManager defaultManager]requestImageForAsset:asset targetSize:CGSizeMake(50,50) contentMode:PHImageContentModeAspectFill options:imageRequestOptions resultHandler:^(UIImage * _Nullable result, NSDictionary * _Nullable info) {
NSLog(#"You get an image from result");
}];
}];
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"]];