应用程序包中文件的路径

4

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

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}

有什么想法吗?

néelam的答案:https://dev59.com/PW025IYBdhLWcg3wAxF9 - user523234
1个回答

14

文件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输出:
文件URL:file:///path/file.txt
网络URL:path/file.txt


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接