views:

1133

answers:

2

My app is accessing data from a remote XML file. I have no issues receiving and parsing the data. However, I'd like to take the most current XML data and store it locally so - in the event that the user's internet service isn't available - the local data from the previous load is used.

Is there a simple way to do this? Or am I going to have to create an algorithm that will create a plist as the xml data is parsed? That seems rather tedious... I was wondering if there was an easier way to save the data as a whole.

Thanks in advance!

+2  A: 

I don't know what format your XML data is in as you receive it, but using NSData might be helpful here, because it has very easy-to-use methods for reading/writing data from either a URL or a pathname.

For example:

NSURL *url = [NSURL URLWithString:@"http://www.fubar.com/sample.xml"];
NSData *data = [NSData dataWithContentsOfURL:url];  // Load XML data from web

// construct path within our documents directory
NSString *applicationDocumentsDir = 
   [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
NSString *storePath = [applicationDocumentsDir stringByAppendingPathComponent:@"sample.xml"];

// write to file atomically (using temp file)
[data writeToFile:storePath atomically:TRUE];

You can also easily convert an NSData object to/from a raw buffer (pointer/length) in memory, so if your data is already downloaded you might do:

    NSData *data = [NSData dataWithBytes:ptr length:len];   // Load XML data from memory
    //  ... continue as above, to write the NSData object to file in Documents dir
David Gelhar
This definitely seems to be the simple solution I was hoping for. Thank you very much!
Charles S.
This is a good solution, but if you are parsing the XML into an NSArray or NSDictionary, it is better to just save the array or dictionary so that you don't have to parse the data in the cache every time you want to read it. Both NSArray and NSDictionary have the methods writeToFile and initWithContentsOfFile
Brian Cooley
A: 

awsome but how to pass this to NSXML parser

how to pass local path to NSXMLParser

like this

NSXMLParser *xmlParser = [[NSXMLParser alloc] initWithContentsOfURL:storePath];

where storepath is my localpath

like this /var/mobile/Applications/56EEB906-2B73-493C-9BE7-2732440CDB69/Documents/xml1.php

ram