Search code examples
iosobjective-cxcodexml-parsingfeed

Parsing feed, what's the best way to save it locally?


I am learning Objective-C and doing a couple personal projects apps.

I am parsing a news feed and showing in a tableview, everything is working. But everytime i open the app, i have to load again the whole feed, and load all the news again.

I was wondering, what's the best way to save those news in a local storage, and everytime i open the app, just make check on the feed to see if there are new news and complement the local storage, so i can fill the tableview with the local saved news only?

Right now i am using RaptureXML to iterate through the items and doing like this:

-(void)fetchRssWithURL:(NSURL*)url complete:(RSSLoaderCompleteBlock)c{
    dispatch_async(kBgQueue, ^{

        RXMLElement *rss = [RXMLElement elementFromURL: url];
        RXMLElement* title = [[rss child:@"channel"] child:@"title"];
        NSArray* items = [[rss child:@"channel"] children:@"item"];

        NSMutableArray* result = [NSMutableArray arrayWithCapacity:items.count];
        cachedImages = [[NSMutableArray alloc] init];

        if(items) {
            for (RXMLElement *e in items) {
                RSSItem* item = [[RSSItem alloc] init];
                item.title = [[e child:@"title"] text];
                item.description = [[e child:@"description"] text];
                item.link = [NSURL URLWithString: [[e child:@"link"] text]];
                item.content = [[e child:@"encoded"] text];
                [result addObject: item];
            }
        }

        c([title text], result);
    });
}

Solution

  • The easiest way to do this IMO is to format your feed data into a nested NSArray/NSDictionary structure and the write it directly to disk. If you stick to Foundation data types then the file will be tiny and in plist format.

    If you stored the data as an array you would write the file to disk by doing something like this

    [array writeToFile:[NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES).firstObject stringByAppendingPathComponent:@"localdata.plist"] atomically:YES];
    

    You could check to see if the file exists by using something like this

    if (![[NSFileManager defaultManager] fileExistsAtPath:path]){}
    

    and if the file is found

    [[NSArray arrayWithContentsOfFile:yourFile] enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
    }
    

    to process the data into a format that would be friendly to your tableview.