应用程序包中的文件路径

时间:2014-02-25 01:59:28

标签: ios ios7 swift nsxmlparser

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

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}

任何人的想法?

1 个答案:

答案 0 :(得分:14)

文件网址和网络网址不同 来自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输出:
fileURL:file:///path/file.txt
netURL:path / file.txt