简体   繁体   中英

Embedding XML to iOS application

I'm making my first game in iOS and I need to load some levels that are stored as XML. Level files are stored locally and everything works fine from emulator. However, since XML is loaded in the runtime when i try to test my game on an actual device it can't find the XML files since they are not actually part of the app.

I'm coming from Flash background so I might have a wrong idea how this is done on iOS but I need to somehow bundle those XML files with the app, or embed it in the code somehow? Is this possible?

Thanks a lot :)

Well The code to look up your app bundle for the specified file is

NSString *path = [[NSBundle mainBundle] pathForResource:@"fileName.xml" ofType:nil]
NSURL *xmlURL = [NSURL fileURLWithPath:path];
[[NSXMLParser alloc] initWithContentsOfURL: xmlURL]

Hope this helps you...

You could add the XML file to your project and run time read it up with something like this

NSArray *myPathList = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);

NSString  *myPath = [myPathList  objectAtIndex:0];
NSError  **err;
myPath = [myPath stringByAppendingPathComponent:fileName];

if([[NSFileManager defaultManager] fileExistsAtPath:myPath])
    text = [NSString stringWithContentsOfFile:myPath encoding:NSUTF8StringEncoding error:err];

You could consider using JSON in instead of XML. At least to my knowledge the available XML parsers are not nearly as simply to use as SBJson for instance (https://github.com/stig/json-framework/)

Here is my solution in Swift 3.0. In addition to the code, you'll need to add your xml file as a data set in your Assets.xcassets. Do this by creating a new Data Set, giving it any name, and then dragging the xml file from the finder to your newly created data set. When you reference the file in your code, you'll use the file name of the file, and not the name of the data set.

var parseResults = false

if let path = Bundle.main.path(forResource: fileName, ofType: ".xml") {
    let url = URL(fileURLWithPath: path)
    if let xmlParser = XMLParser(contentsOf: urlToFile) {
        xmlParser.delegate = self
        parseResults = xmlParser.parse()
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM