简体   繁体   English

将XML嵌入到iOS应用程序

[英]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. 我正在用iOS开发我的第一款游戏,我需要加载一些存储为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. 但是,由于XML是在运行时加载的,因此当我尝试在实际设备上测试游戏时,找不到XML文件,因为它们实际上不是应用程序的一部分。

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? 我来自Flash背景,因此我可能对iOS上的操作方法有一个错误的认识,但我需要以某种方式将这些XML文件与应用程序捆绑在一起,或以某种方式将其嵌入代码中? 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 您可以将XML文件添加到您的项目中,然后在运行时使用类似的内容进行读取

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. 您可以考虑使用JSON而不是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/) 至少据我所知,可用的XML解析器不像SBJson那样简单地使用(https://github.com/stig/json-framework/)

Here is my solution in Swift 3.0. 这是我在Swift 3.0中的解决方案。 In addition to the code, you'll need to add your xml file as a data set in your Assets.xcassets. 除了代码之外,您还需要将XML文件作为数据集添加到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. 为此,请创建一个新的数据集,为其命名,然后将xml文件从查找器中拖动到新创建的数据集。 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()
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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