Search code examples
iosobjective-cxmlnsxmlparser

Enumerate thru items in XML feed


I have a collection view that shows the results of an XML feed. It works great, but I need to save the results of the XML feed locally (if no internet connection available for example).

I know how to save the raw feed locally, but I think what I really need to be doing is iterating thru the items in the XML feed and saving each as a NSData item.

Is that the right way to think about it, or do you have any useful advice or tips?

- (void)startParsing
{
    NSXMLParser *xmlparser = [[NSXMLParser alloc] initWithContentsOfURL:[NSURL URLWithString:@"http://images.apple.com/main/rss/hotnews/hotnews.rss#sthash.TyhRD7Zy.dpuf"]];
    [xmlparser setDelegate:self];
    [xmlparser parse];
    if (_marrXMLDataCollection.count != 0) {
        // Save XML to NSData items in background?

        [self.collectionView reloadData];
    }
}

Here's an example of what the feed looks like, and I have this stored in the Documents directory as localdata.plist too:

(
        {
        link = "\nhttp://www.apple.com/pr/library/2016/04/26Apple-Reports-Second-Quarter-Results.html?sr=hotnews.rss";
        pubDate = "\nTue, 26 Apr 2016 14:44:21 PDT";
        title = "\nApple Reports Second Quarter Results";
    },
        {
        link = "\nhttp://www.apple.com/final-cut-pro/in-action/trim-editing/?sr=hotnews.rss";
        pubDate = "\nWed, 20 Apr 2016 10:05:59 PDT";
        title = "\n\nFinal Cut Pro X helps small company delight world\U2019s biggest clients";
    },
        {
        link = "\nhttp://www.apple.com/ipad-pro/?sr=hotnews.rss";
        pubDate = "\nMon, 21 Mar 2016 12:00:03 PDT";
        title = "\n\nApple Introduces 9.7-inch iPad Pro";
    },
        {
        link = "\nhttp://www.apple.com/iphone-se/?sr=hotnews.rss";
        pubDate = "\nMon, 21 Mar 2016 11:58:09 PDT";
        title = "\n\nApple Introduces iPhone SE \U2014 the Most Powerful Phone with a 4-inch Display";
    },

Solution

  • You can just save the XML directly to a file, either as binary data or text. You don't need to unpack it and convert it to anything. Later you can then load the fine and re-run your parsing code. This is the least code option. It's more runtime costly but unless your XML file is rather large you won't notice the difference.

    If you want to save the processed content then your XML should be getting turned into an array of model objects and you can implement NSCoding on those model objects to allow you to archive them to disk. This should be more runtime efficient but is also more code.