iOS offline cache

Source: Internet
Author: User

In order to save traffic and better user experience, many applications now use the local cache mechanism, do not need to load data every time the app is opened, or to re-request data to the server, so you can save each browsing data to the sandbox, the next time you open the software, first load the cached data from the sandbox, Or, when the app is not networked, load the old cached data from the sandbox.

Method selection of offline data
    1. plist file
    2. Document Path
    3. Database

You should choose a database to store because you are saving large amounts of data and you are constantly refreshing new data. Using a database allows for fast data read operations.

1. Design Ideas

For example, the process of offline caching is illustrated:


Offline caching
    1. When you open the app for the first time, save the data from the server to the sandbox;
    2. The next time you enter the app, look in the sandbox first, and if the previous data is saved in the sandbox, the data in the sandbox is displayed;
    3. If there is no network, load the data saved to the sandbox directly.
2. Practical Application
Example

The following is an example program that describes offline caching. The framework used by the sample program has fmdb,sdwebimage,afnetworking, and the data is an open API provided by aggregated data.

JSON return example
{    "ResultCode ":"200", "Reason ":"Success", "Result ":{ "Data ":[ { "ID ":"1001", "Title ":"Sweet and sour Little Platoon", "Tags ":"Zhejiang cuisine; hot dishes; children; sour and sweet; quick starters", "Imtro ":"Sweet and sour small row, I estimate love to eat too many people, to want to do this dish, the key is the configuration of the sauce, the old smoking can not put too much, so the color is too heavy, not good-looking, seasoning juice adjusted, the best taste, everyone's taste will be different, can be appropriate fine-tuning ha!" ", "INGREDIENTS ":"Ribs, 500g", "Burden ":"Onion, right amount; white sesame seeds, right amount; salt, 3g; raw flour, 45g; cooking wine, 30ml; eggs, 1; onion, 1 small segments; ginger, 3 slices, old smoke, 7ml, vinegar, 30ml, sugar, 20g, tomato sauce, 15ml, soy, 15ml, raw powder, 7g; ginger, right amount", "Albums ":["Http://img.juhe.cn/cookbook/t/1/1001_253951.jpg"], "Steps ":[ { "IMG ":"Http://img.juhe.cn/cookbook/s/10/1001_40ec58177e146191.jpg", "Step ":"1. Chop small pieces of ribs, wash with water repeatedly, remove blood"}, {"IMG ":"Http://img.juhe.cn/cookbook/s/10/1001_034906d012e61fcc.jpg", "Step ":"2. Put the ribs into the container, add the marinade, stir evenly, marinate for 5 minutes"}, {"IMG ":"Http://img.juhe.cn/cookbook/s/10/1001_b04cddaea2a1a604.jpg", "Step ":"3. Put the right amount of oil in the pot, burn to 50% heat, pour ribs, fry to take out the green smoke, close the fire, and other oil temperature to 50% heat, fire, put the ribs again, medium fire fried to brown, cooked out"}, {"IMG ":"Http://img.juhe.cn/cookbook/s/10/1001_56b92264df500f01.jpg", "Step ": " 4. Leave a little base oil in the pan, add the chopped green onion, ginger slices of incense "}, {"img ": " http://img.juhe.cn/cookbook/s/10/1001_ D78c57536a08dc4b.jpg ","Step ": " 5. Put the right amount of fried ribs, pour into the sauce, boil until the broth is thick, turn off the fire, sprinkle with chopped green onion, white sesame dot can be "}]}],"totalnum ": 1," C12>PN ": 0,"rn ": 1},"error_code ": 0}        
In the SQLITEMANAGER.M

Single Example:

// 单例+(SQLiteManager *)sharedInstance {    @synchronized(self) {        if (shareObj == nil) { shareObj = [[self alloc] init]; } } return shareObj;}

Initialization of the database:

Initialize Database-(instancetype) init {if (Self = [Super Init]) {File pathNSString *path = [[Nssearchpathfordirectoriesindomains (NSDocumentDirectory,Nsuserdomainmask,yes) Lastobject] Stringbyappendingpathcomponent:@ " Step.sqlite "]; //Initialize database self.database = [ Fmdatabase Databasewithpath:path]; //Open the database [self.database Open]; Span class= "Hljs-keyword" >if ([self.database Open]) {//the Step takes a blob type to store nsstring *create = @ "CREATE TABLE IF not EXISTS t_step (ID integer PRIMARY KEY, step blob not NULL);"; [self.database Executeupdate:create];}} return self;}        

To get data from a database:

//从数据库获取数据-(NSArray *)stepsFromSqlite {    NSString *sql = @"SELECT * FROM t_step";    FMResultSet *set = [self.database executeQuery:sql]; NSMutableArray *steps = [NSMutableArray array]; while (set.next) { NSData *data = [set objectForColumnName:@"step"]; Steps *step = [NSKeyedUnarchiver unarchiveObjectWithData:data]; [steps addObject:step]; } return steps;}

To save data to a database:

// 保存数据到数据库-(void)saveSteps:(Steps *)step {    NSData *data = [NSKeyedArchiver archivedDataWithRootObject:step];    [self.database executeUpdateWithFormat:@"INSERT INTO t_step(step) VALUES (%@);", data];}
In MENUTABLEVIEWCONTROLLER.M

Get Server data:

Get Server Data-(void) GetData {Afhttpsessionmanager *session = [[Afhttpsessionmanager alloc] init];NSString *url =@ "Http://apis.juhe.cn/cook/queryid";Nsmutabledictionary *params = [Nsmutabledictionary dictionary]; params[@ "id"] =Self. MenuID; params[@ "key"] =Self. AppKey; params[@ "Dtype"] =Self. Dtype;Getting data from a databaseNsarray *steps = [[Sqlitemanager sharedinstance] stepsfromsqlite];if (steps. Count) {Self. Stepsarray = [Nsmutablearray Arraywitharray:steps]; }else {Get request, fetch data from server [session Get:url Parameters:params Progress:Nil success:^ (Nsurlsessiondatatask * _nonnull task,ID _nullable responseobject) { Nsdictionary *result = responseobject[@ "result"]; Nsarray *data = result[@ "Data"]; For (nsdictionary *dict in data) {Menu *menu = [[Menu alloc] initwithdict:dict]; self. stepsarray = Menu. Steps;} [self. TableView reloaddata];} failure:^ (nsurlsessiondatatask * _nullable task, nserror * _nonnull Error) { NSLog (@ "error=%@", error);}];}}            
3. Clear the picture

Such as:


Clear picture

A method for getting the current cache size and clearing the cache is provided in Sdimagecache.

In MENUTABLEVIEWCONTROLLER.M

Get Current Cache Size:

//字节大小int byteSize = (int)[SDImageCache sharedImageCache].getSize;//M大小CGFloat cacheSize = byteSize / 1000.0 / 1000.0;UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"清理缓存" message:[NSString stringWithFormat:@"缓存大小%.1fM",cacheSize] delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];[alert show];

Clear cache:

//清除缓存[[SDImageCache sharedImageCache] clearDisk];
4. File operation

You can use Sdimagecache to clear the cache of pictures, but some caches are not image caches, such as video files or MP3 files that users temporarily watch, and if you want to clear them, use the file operation method to traverse the Library/cache folder in the sandbox. Figure out the size of the cache folder and erase all the cached files.

注:文件夹是没有大小的,只有文件有大小属性。
Calculate the size of the current folder-(Nsinteger) Cachesfilesize {File ManagerNsfilemanager *mgr = [Nsfilemanager Defaultmanager];Determine if the file isBOOL dir =NO;BOOL exists = [Mgr Fileexistsatpath:Self isdirectory:&dir];if (!exists)Return0;The description file or folder does not existif (dir) {Self is a folderTraverse the contents of caches-direct and indirect contentNsarray *subpaths = [Mgr Subpathsatpath:Self];Nsinteger totalbytes =0;If self is a folder, traverse the file under that folderfor (NSString *subpathIn subpaths) {//Get full path nsstring *fullpath = [selfstringbyappendingpathcomponent:subpath]; BOOL directory = NO; [Mgr Fileexistsatpath:fullpath isdirectory:&directory]; if (!directory) { //Self is not a folder, calculate the size of the file totalbytes + = [[Mgr Attributesofitematpath:fullpath error:nil][  Nsfilesize] IntegerValue]; }} return totalbytes;} else { //self is a file return [[Mgr Attributesofitematpath: Selferror:nil][Nsfilesize] IntegerValue]; }}



Wen/hrscy (author of Jane's book)
Original link: http://www.jianshu.com/p/426c66e46f9e
Copyright belongs to the author, please contact the author to obtain authorization, and Mark "book author".

iOS offline cache

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.