把图片缓存到本地,在很多场景都会用到,如果是只储存文字信息,那建一个plist文件,或者数据库就能很方便的解决问题,但是如果存图片到沙盒就没那么方便了。这里介绍两种保存图片到沙盒的方法。
I. Convert the image into a base64 string into a database or plist file, and then remove it when you use it.
//get sandbox path, NSString *path_sandox = Nshomedirectory (); //create a path to store plist files nsstring *newpath = [Path_sandox stringbyappendingpathcomponent:@"/documents/pic.plist "]; nsmutablearray *arr = [[nsmutablearray alloc ] init]; //convert the picture to a Base64 string nsstring *image64 = [self Encodetobase64string:image]; [Arr addobject:image64]; //writing plist file if ([arr writetofile:newpath atomically:yes ]) {nslog (@ "Write succeeded" ); };
And then save it and use it to convert the stored string into a picture.
*_decodedImageData = [[NSData alloc] initWithBase64Encoding:image64]; *_decodedImage = [UIImage imageWithData:_decodedImageData];
Two. Save the picture directly to the sandbox, and then store the path, and then take the path to the image and get the picture by the path.
//拿到图片UIImage *image = [UIImage imageNamed:@"flower.png"NSString *path_sandox = NSHomeDirectory();//设置一个图片的存储路径NSString *imagePath = [path_sandox stringByAppendingString:@"/Documents/flower.png"];//把图片直接保存到指定的路径(同时应该把图片的路径imagePath存起来,下次就可以直接用来取)[UIImagePNGRepresentation(image) writeToFile:imagePath atomically:YES];
Next time use the address of the picture to get the picture directly.
Also attach the code to get the sandbox directory
Sandbox file directory get code:
Home Directory
NSString *homeDirectory = NSHomeDirectory();
Document Directory
NSArrayYES); NSString *path = [paths objectAtIndex:0];
Cache Directory
NSArrayYES); NSString *path = [paths objectAtIndex:0
Libaray Directory
NSArrayYES); NSString *path = [paths objectAtIndex:0];
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Several ways that iOS caches pictures locally