How to save an image in the application cache and display later?

0

I was assigned to before launching the application displaying promotional images. Images are obtained through JSON, which also has a preview time setting.

I am using the following code to store the image 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 take the image directly from the URL it works but not the cache.

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

Who could give me a glimpse into this process of image caching? It does not give an error but the images are all black when obtained from the cache.

    
asked by anonymous 07.10.2014 / 20:12

1 answer

2

Have you created the directory you are trying to save?

Creation code:

-(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 that is very explanatory.

    
10.10.2014 / 22:12