How to cache an image from the application and display it later?

Asked

Viewed 281 times

0

I was assigned to before starting the app to display promotional images. Images are obtained through JSON, which also has a display time setting.

I am using the following code to store the image coming from a URL in the /Library/Caches/Images directory/:

// /Library/Caches
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSLocalDomainMask, YES);
// /Library/Caches/Images
NSString *path = [[paths objectAtIndex:0] stringByAppendingPathComponent:@"Images"];

NSString *extension = [imageURLString pathExtension];
// /Library/Caches/Images/image_0.jpg
NSString *filePath = [path stringByAppendingPathComponent:[NSString stringWithFormat:@"image_%d.%@", index, extension]];
NSData *file = [NSData dataWithContentsOfURL:[NSURL URLWithString:imageURLString]];
[file writeToFile:filePath atomically:YES];
[self.imagesCache addObject:filePath];

Then to display the images I’m using the code:

// Dentro de um loop. current é o índice do loop
UIImage *image = [UIImage imageWithContentsOfFile:[self.imagesCache objectAtIndex:current]];
self.currentImage = [[UIImageView alloc] initWithImage:image];

When I get the image directly from the URL it works, but the cache does not.

self.currentImage = [[UIImageView alloc]
                 initWithImage:[UIImage
                                imageWithData:[NSData
                                               dataWithContentsOfURL:[NSURL URLWithString:imageURLString]]]];

Who could shed some light on this image caching process? No error, but the images are all black when retrieved from the cache.

  • You have checked whether the method really writeToFile:atomically: is returning YES? You may not even be saving the image.

  • This link may clarify your question. 
 
 http://stackoverflow.com/questions/10784278/how-to-cache-images-in-iphone

1 answer

2


You have created the directory in which you are trying to save?

Code for creation:

-(void)createDirectory:(NSString *)directoryName atFilePath:(NSString *)filePath
{
    NSString *filePathAndDirectory = [filePath stringByAppendingPathComponent:directoryName];
    NSError *error;

    if (![[NSFileManager defaultManager] createDirectoryAtPath:filePathAndDirectory
                                   withIntermediateDirectories:NO
                                                    attributes:nil
                                                         error:&error])
    {
        NSLog(@"Create directory error: %@", error);
    }
}

I also found this tutorial which is very explanatory.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.