Sunday, May 1, 2011

Compiling an XML file into a binary

I want to parse and XML file in an iPhone app without going to disk for it. Can I do this? How? I have included a TXT helpfile in an app using MSVC.

I put the XML file in a Folder/Group named Resources in the project.
I have the XML file in the proj directory.
I right clicked on Resources folder and selected add -> Existing File.
I right-click on the XML file and select GetInfo.

There I have tried altering the Path Type {Absolute, Relative to Project , etc}
My program runs fine on the simulator when I use:

NSString * const DG_XmlRecipeFile = @"/Users/appleuser/Cocoa/iHungry6/Recipes.xml";

It seems to me it should also work with:

NSString * const DG_XmlRecipeFile = @"Recipes.xml";

If I set the Path Type correctly. It does not.

I am a first timer. Thanks for reading this , Mark

From stackoverflow
  • Xcode copies the project resources to the app bundle. You can access your file within your bundle as follows:

    NSString *DG_XmlRecipeFile = [[NSBundle mainBundle] pathForResource:@"Recipes" ofType:@".xml"];
    

    Files in the bundle are read-only. If you want to modify the file you will need to copy it somewhere that you can modify it. Your app's Documents directory works well for this.

    NSArray  *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *docsDirectory = [[paths objectAtIndex:0] retain];
    NSString *newFilePath = [docsDirectory stringByAppendingPathComponent:@"Recipes.xml"];    
    NSError  *error = nil;
    
    [[NSFileManager defaultManager] copyItemAtPath:DG_XmlRecipeFile toPath:newFilePath error:&error];
    
    mbarron : This is great. Thanks for your time. It is great to have you guys out there.
    mbarron : Your answer lead me to the following : NSString *DG_XmlRecipeFile = [[NSBundle mainBundle] pathForResource:@"DG_Recipes" ofType:@"xml"]; You not only solved my problem but also gave me a better understanding of home the iPhone handles platform independent paths, while trying to reach a copy of the file referenced in the Project Resources Group folder. I am very much in your debt. Many thanks, Mark
  • I don't think the path type you are referring to is the path to the resource within the app bundle that is produced. It is how the file should be referenced within the .proj file.

    mbarron : Thanks for you answer. I appreciate you taking the time.

0 comments:

Post a Comment

Note: Only a member of this blog may post a comment.