Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Path to file in app bundle

I did this many times before but now it fails. I want to access a file shipped within my app.

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

returns

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

which is correct - checked in terminal and all that. However, trying to parse the path fails

    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;
    }

with

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

Ideas anyone?

like image 691
El Dude Avatar asked Dec 08 '22 09:12

El Dude


1 Answers

File URLs and network URLs are different.
From the Apple documentation:

Important: To create NSURL objects for file system paths, use
fileURLWithPath:isDirectory:
or just
fileURLWithPath:

Example:

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

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

NSLog Output:
fileURL: file:///path/file.txt
netURL: path/file.txt

like image 176
zaph Avatar answered Dec 11 '22 09:12

zaph