Several Methods for IOS to cache images locally
Caching images locally is used in many scenarios. If you only store text information, you can create a plist file or database to easily solve the problem, however, it would be less convenient to store images in a sandbox. Here we will introduce two methods for saving images to the sandbox.
I. Save the image to a base64 string in the database or plist file, and then extract it when it is used.
// Obtain the sandbox path, NSString * path_sandox = NSHomeDirectory (); // create a path to store the plist file NSString * newPath = [path_sandox stringByAppendingPathComponent: @/Documents/pic. plist]; NSMutableArray * arr = [[NSMutableArray alloc] init]; // converts an image to a Base64 string NSString * image64 = [self encodeToBase64String: image]; [arr addObject: image64]; // write the plist file if ([arr writeToFile: newPath atomically: YES]) {NSLog (@ write successful );};
In this way, the stored strings are used to convert them into images.
NSData *_decodedImageData = [[NSData alloc] initWithBase64Encoding:image64]; UIImage *_decodedImage = [UIImage imageWithData:_decodedImageData];
2. Save the image directly to the sandbox, and then store the path. When the image is used, the image path is obtained first, and then the image is obtained through the path.
// Obtain the image UIImage * image = [UIImage imageNamed: @flower.png]; NSString * path_sandox = NSHomeDirectory (); // set the storage path of an image NSString * imagePath = [path_sandox stringByAppendingString: @/Documents/flower.png]; // Save the image directly to the specified path (the image path imagePath should be saved at the same time and can be directly used next time) [UIImagePNGRepresentation (image) writeToFile: imagePath atomically: YES];
Next time, use the image address to get the image directly.
The code for obtaining the sandbox directory is also attached.
Code for obtaining the sandbox file directory:
// Home directory
NSString *homeDirectory = NSHomeDirectory();
// Document directory
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); NSString *path = [paths objectAtIndex:0];
// Cache directory
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES); NSString *path = [paths objectAtIndex:0];
// Libaray directory
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES); NSString *path = [paths objectAtIndex:0];