开发者

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 d开发者_如何学Pythonata 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!


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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜