How to cache or store parsed xml file? - iphone

My app parses an xml file from my server, but I want to store parsed xml file and next start of my app, controller initially should load stored xml file, then controller should parse it again to check that there may be an update I did on xml file, if there is, new elements parsed should also be stored again.
I am referring to those app such as magazines, newspaper apps. When you open those kind of apps, it loads stored data that was downloaded previous session. Yet, after it loads, it starts to update the data, and it stores new update again.
Where do I start? What do you guys suggest?
Thanks in advance...

You can use CoreData or SQLite (use Objective-C wrapper FMDB https://github.com/ccgus/fmdb) to persist your XML. Then update the database everytime you see a unique id. Depends on how your XML data is.

It's actually quite easy to store to the documents directory. For example:
NSData *data; //this is your xml file
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *docs = [paths objectAtIndex:0];
NSString *filename = [NSString stringWithFormat:#"test.xml"];
NSString *path = [docs stringByAppendingPathComponent:filename];
[data writeToFile:path atomically:YES];
Then to retrieve it later, you can get the path like above, but retrieve the file instead of writing it:
NSData *data = [NSData dataWithContentsOfFile:path];

either CoreData or SQLite can do the trick

Related

write into plist file using NSDictionary object

Sorry I saw similar questions but they don't seem to have some full answers for me. And i try to put it in order so that people will not hate me or my poor english.
I am working with Xcode 4.2 with storyboard and ARC
I can read from my plist file. My task is simply to write back the updated value(s) to my plist file.
My plist is contain in "supporting files" sub folder of the main folder (where story-board is things goes). the file is call Global.plist and GlobalValue2 is a element of the file type string.
So the read file part looks like this
NSString *plistfile = [[NSBundle mainBundle] pathForResource:#"Global" ofType:#"plist"];
NSDictionary *dict = [NSDictionary dictionaryWithContentsOfFile:plistfile];
FirstValueTextBox.text = [[dict valueForKey:#"GlobalValue1"] stringValue];
learn it from some handy youtube video works just fine. updates the value to my text box.
The real problem comes in when I write back my plist file. When i try the following
NSString *plistfile = [[NSBundle mainBundle] pathForResource:#"Global" ofType:#"plist"];
NSMutableDictionary *dict = [NSMutableDictionary
dictionaryWithContentsOfFile:plistfile];
[dict setValue:#"ABC" forKey:#"GlobalValue2"];
SecondValueTextBox.text = [dict valueForKey:#"GlobalValue2"];
[dict writeToFile:plistfile atomically:YES];
the result is I really saw a updated value pop up on the second text box, but the plist file remain unchanged.
The following are the break down of my questions and my guess for the problem
I try to use NSDictionary(not NSMutableDictionary) and call setValue (crash in runtime)
my guess: NSDictionary object itself is readonly so it crash me when i say add value. But why don't it error me when in coding time? if the object is readonly
I use NSMutableDictionary can call setValue. it doesn't crash me and when i call the updated value at "SecondValueTextBox.text = [dict valueForKey:#"GlobalValue2"];" it really return me the updated value. but the content inside of the plist file is not changed. Which is the result I have right now.
my guess: after some search here and there I think "supporting files" is read only too. pure guess did see anyone directly talk about it.
I did try to move on a little more and some people talks about a "document folder" in Xcode that is a read and write place. I think people also talk about write a code to access that folder. Can someone show me the code here.
My last question, can I hook up my Xcode to that "document folder" or where can i see it(the real file folder structure is different from inside Xcode I think). So that i can see and edit my plist file for testing, and i can see the real result without using codes and stuff
I will be much appreciated if people can tell me my guess is right or wrong and the answer to my 3 and 4 question.
In order for your changes to be persisted in your plist, you would indeed need ot copy it from the resource bundle to the documents dirtectory on launch of the application, then use the plist in the documents to read and write.
Here is how you can copy the file:
NSFileManager *fileManager = [NSFileManager defaultManager];
NSError *error;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *plistPath = [documentsDirectory stringByAppendingPathComponent:#"Global.plist"];
if ([fileManager fileExistsAtPath:plistPath] == NO) {
NSString *resourcePath = [[NSBundle mainBundle] pathForResource:#"Global" ofType:#"plist"];
[fileManager copyItemAtPath:resourcePath toPath:plistPath error:&error];
}

i have xml file in my application that i want to write data into it

I have this xml file:
<?xml version="1.0" encoding="UTF-8"?>
<Favorites>
<favorite id="1">
<title>My first favorite</title>
<latitude>31.369834</latitude>
<longitude>34.798207</longitude>
</favorite>
</Favorites>
and I want to write more "favorite"s into it.
I have all the data I need as strings in my project.
But I can't figure out how to really do it - although I have tried a lot.
can you please help me do it ?
thanks.
I agree with the responders that you should consider using a .plist file. Creating NSDictionary objects of your "Favorite" objects, and saving the array of them.
But, to your immediate question, you could save a NSString representing your XML like this (but again, saving a string based XML means a lot of parsing and interaction methods created by you):
// Build The Path
//
NSArray * paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
NSUserDomainMask,
YES);
NSString * filePath = [paths objectAtIndex:0];
filePath = [filePath stringByAppendingPathComponent:#"favorites"];
filePath = [filePath stringByAppendingPathExtension:#"xml"];
// You Should Have A "Favorite" Objects That Know How To Desribe Themselves...
//
NSString * badWayToDoThis = #"<ThinkAboutUsingDictionaries>Saving The Data to a plist</seriously>";
[badWayToDoThis writeToFile:filePath
atomically:YES
encoding:NSUTF8StringEncoding
error:NULL];
Hope that at the very least gets you towards where you're headed.
You could use a plist and create functions that:
First - creates an array or dictionary from the plist
Second - adds new values to your array/dictionary
Third - saves the dictionary to the same file, overwriting and updating the old version.
So rather that inserting values you just overwrite with an updated version

Including Core Data in app bundle

I'm not sure that I completely understand how Core Data works on iOS.
I have a large JSON file which I have parsed and imported into core data. This generates an sqlite file. I need this file to be included with the app but every time I delete the app from the device - I have to run the JSON parse script again to create a new sqlite file on the device. I want to be able to exclude the JSON file from the application bundle and dont want to run the parsing script on first use.
How do I go about doing this? Am I doing something wrong?
You will need to create the sqlite file (using your app if you like), then copy it into your project and deploy it with the app. You will also need to add some code to move the file into your documents directory when your app runs for the first time. It can be a simple if file doesn't exist then copy it script.
NSFileManager *fileManager = [NSFileManager defaultManager];
NSError *error;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *DB = [[paths lastObject] stringByAppendingPathComponent:#"myDB.sqlite"];
if (![fileManager fileExistsAtPath:DB]) {
NSString *shippedDB = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:#"myDB.sqlite"];
[fileManager copyItemAtPath:shippedDB toPath:DB error:&error];
}
I use this method to ship out pre-built sqlite files, although I haven't used it when CoreData is managing the sqlite file.

Simplest way on iPhone to unzip downloaded file?

Goal: download a zipped file, unzip it, and save it in the iPhone app's Documents directory.
The following code makes use of the initWithGzippedData method that was added to NSData in the Molecule app found here:
http://www.sunsetlakesoftware.com/molecules
As adapted to my app:
NSString *sFolder = [NSHomeDirectory() stringByAppendingPathComponent:#"Documents"];
NSString *sFileName = [sFolder stringByAppendingPathComponent:#"MyFile.db"];
NSURL *oURL = [NSURL URLWithString: #"http://www.isystant.com/Files/MyFile.zip"];
NSData *oZipData = [NSData dataWithContentsOfURL: oURL];
NSData *oData = [[NSData alloc] initWithGzippedData:oZipData];
[oZipData release];
b = [oData writeToFile:sFileName atomically:NO];
NSLog(#"Unzip %i", b);
Result: A zip file is successfully downloaded. From it a new, supposedly unzipped file is created in the Documents directory with the desired name (MyFile.db) but it has zero bytes.
Anybody see the problem? Or else is there a simpler way to unzip a downloaded file than the one used in the Molecules app?
I think that your problem may be that you are attempting to gzip-deflate a Zip file. Those are two different compression algorithms.
I based the gzip-deflating code in Molecules on this NSData category (the code of which I've copied into this answer) provided by the contributors to the CocoaDev wiki. What you'll want to do is use their -zlibDeflate implementation, which should properly unzip a Zip file.
Unrelated to your problem, instead of using NSHomeDirectory() and appending a path component, the recommended approach for finding the documents directory is the following:
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
You should make sure your file is never too big, as you are loading it fully into memory before the unzip starts.

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!
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