user2393462435
user2393462435

Reputation: 2652

How can I locally save an XML file on an iPhone for when the device is offline?

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!

Upvotes: 2

Views: 9827

Answers (1)

David Gelhar
David Gelhar

Reputation: 27900

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

Upvotes: 9

Related Questions