【问题标题】:Path to file in app bundle应用程序包中的文件路径
【发布时间】:2014-03-27 00:33:52
【问题描述】:

我以前做过很多次,但现在失败了。 我想访问我的应用程序中附带的文件。

NSString* path = [[NSBundle mainBundle] pathForResource:@"information" ofType:@"xml"];

返回

/Users/eldude/Library/Application Support/iPhone Simulator/7.0.3/Applications/5969FF96-7023-4859-90C0-D4D03D25998D/App.app/information.xml

这是正确的 - 在终端中检查等等。但是,尝试解析路径失败

    NSURL* fileURL = [NSURL URLWithString:path];

    NSXMLParser *nsXmlParser = [[NSXMLParser alloc] initWithContentsOfURL:fileURL];

    [nsXmlParser setDelegate:self];

    if(![nsXmlParser parse]){
        NSError* e = nsXmlParser.parserError;
        NSLog(@"ERROR parsing XML file: \n %@",e);
        self = NULL;
    }

Error Domain=NSCocoaErrorDomain Code=-1 "The operation couldn’t be completed. (Cocoa error -1.)" UserInfo=0xb9256f0 {NSXMLParserErrorMessage=Could not open data stream}

有什么想法吗?

【问题讨论】:

标签: ios ios7 swift nsxmlparser


【解决方案1】:

文件 URL 和网络 URL 不同。
来自 Apple 文档:

重要提示:要为文件系统路径创建 NSURL 对象,请使用
fileURLWithPath:isDirectory:
或者只是
fileURLWithPath:

例子:

NSString *filePath = @"path/file.txt";
NSURL *fileURL = [NSURL fileURLWithPath:filePath];
NSLog(@"fileURL: %@", [fileURL absoluteURL]);

NSURL *netURL = [NSURL URLWithString:filePath];
NSLog(@"netURL: %@", [netURL absoluteURL]);

NSLog 输出:
文件网址:file:///path/file.txt
netURL: 路径/file.txt

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-05-13
    • 1970-01-01
    • 2021-04-18
    相关资源
    最近更新 更多