应用程序包中的文件路径

El *_*ude 4 nsxmlparser ios ios7 swift

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

NSString* path = [[NSBundle mainBundle] pathForResource:@"information" ofType:@"xml"];
Run Code Online (Sandbox Code Playgroud)

回报

/Users/eldude/Library/Application Support/iPhone Simulator/7.0.3/Applications/5969FF96-7023-4859-90C0-D4D03D25998D/App.app/information.xml
Run Code Online (Sandbox Code Playgroud)

这是正确的 - 在终端和所有这些检查.但是,尝试解析路径失败

    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;
    }
Run Code Online (Sandbox Code Playgroud)

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

想法有人吗?

zap*_*aph 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]);
Run Code Online (Sandbox Code Playgroud)

NSLog输出:
fileURL:file:///path/file.txt
netURL:path/file.txt