Read & write JSON for caching purpose

/
0 Comments
Hello there! Today I would like to share a tips for caching. As you guys know when loading data (json for this example) into one page in iOS, user must wait a time to connect back office and get them. User experience is not good here if the data show on screen is still the same day to day, it makes the user hate your app (like me :D). So the solution is write the json to document or cache folder and load them if the json is exist.

-(void) saveCacheWithJSON:(id)json {
    if (!baseCacheName) {
        DLog(@"HEY, baseCacheName is nil . DID YOU FORGET TO SET IT?");
        return;
    }
    if([json isKindOfClass:[NSDictionary class]]) {
        NSData *dataToSave =  [NSJSONSerialization dataWithJSONObject:json options:NSJSONWritingPrettyPrinted error:nil];
        NSString    *path = [PATH_DOCUMENT_FOLDER stringByAppendingFormat:@"/%@.json",baseCacheName];
        [dataToSave writeToFile:path atomically:YES];
        
    }
}

-(NSString*) loadCacheString {
    if (!baseCacheName) {
        DLog(@"HEY, baseCacheName is nil . DID YOU FORGET TO SET IT?");
        return nil;
    }

    NSString    *path = [PATH_DOCUMENT_FOLDER stringByAppendingFormat:@"/%@.json",baseCacheName];
    return [NSString stringWithContentsOfFile:path encoding:NSUTF8StringEncoding error:nil];
}
Note that saveCacheWithJSON function the parameter is id 'cause some people is using AFNetworking as a lib to connect BO so JSON string will be removed double quotes "". The best practise is use NSData.


You may also like

No comments:

Member of Mroom Software. Powered by Blogger.