Several ways that iOS caches pictures locally

Source: Internet
Author: User

把图片缓存到本地,在很多场景都会用到,如果是只储存文字信息,那建一个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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.