从应用程序包中解析 XML,而不是 URL
我正在构建一个从在线服务器解析 XML 的应用程序。我想在本地缓存 XML 文件 24 小时。如何更改以下代码以从资源目录中的文件中读取?
parser = [[NSXMLParser alloc] initWithContentsOfURL: [NSURL URLWithString:url]];
I'm building an application that parses XML from an online server. I want to cache the XML file locally for 24 hours. How can I change the following code to read from a file in my resource directory?
parser = [[NSXMLParser alloc] initWithContentsOfURL: [NSURL URLWithString:url]];
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以像下面这样获取 xml 文件的路径:
然后像下面这样获取 NSData 实例:
最后调用
NSXMLParser
的initWithData
方法。但是您无法修改应用程序包的内容。捆绑包中的文件(您请求的资源目录)无法修改。
有不同的方法可以做到这一点:
NSFileManager
类来保存和读取您的xml文件NSFileManager
的示例>:该代码片段获取文档目录中包含的 xml 文件路径。这意味着那里已经有一个文件了。有关详细信息,请参阅 NSFileManager 类 和 如何保存您的应用程序-data-with-nscoding-and-nsfilemanager
希望有帮助。
You can obtain the path for your xml file like the following:
and then obtain a NSData instance like the following:
and finally call
initWithData
method ofNSXMLParser
.But you cannot modify the content of your application bundle. Files in the bundle (the resources directory you asked for) cannot be modified.
There are different way to do it:
NSFileManager
class to save and read your xml fileAn example with
NSFileManager
:The snippet grab the xml file path contained in your Documents directory. It means that there is already a file there. For further info see NSFileManager class and how-to-save-your-app-data-with-nscoding-and-nsfilemanager
Hope it helps.