Search code examples
objective-cmacoscocoansfilemanager

Reading jpeg from file fails with "no such file" but file is clearly there


I'm running into problems reading jpeg files from the file system and displaying the image in an NSImage. Here's a snippet of code:

    NSError *myError;
    NSString *path = @"file:/Users/jpurlia/Documents/Development/Test/1915brsts880804of.jpg";
    NSURL *url = [NSURL fileURLWithPath:path];
    NSData *data = [NSData dataWithContentsOfURL:url
                                         options:0
                                           error:&myError];
    _photoImageView.image = [[NSImage alloc] initWithData:data];

Running this code generates the following error upon calling dataWithContentsOfURL: Error Domain=NSCocoaErrorDomain Code=260 "The file “1915brsts880804of.jpg” couldn’t be opened because there is no such file." And, additionally: {Error Domain=NSPOSIXErrorDomain Code=2 "No such file or directory"}

The file does exist, and if I copy the path and paste it into a web browser, the jpeg image is displayed as expected. I'm guessing this is some kind of permission problem that exists to prevent applications from accessing the file system directly? I had a similar problem when attempting to open files selected from an Open Panel, which turned out to be a problem with running Open/Save Panels from sandboxes, so I turned off sandboxing to get that aspect of my application working.

Does this ring a bell for anyone? I'm kind of baffled...


Solution

  • If you want to create an NSURL using fileURLWithPath then you need to provide a path, not a URL. Remove the use of file:.

    NSString *path = @"/Users/jpurlia/Documents/Development/Test/1915brsts880804of.jpg";
    NSURL *url = [NSURL fileURLWithPath:path];
    

    Or you can fix the file URL and use NSURL URLWithString. Use file:// before the absolute file path so you have 3 /:

    NSString *fileURLString = @"file:///Users/jpurlia/Documents/Development/Test/1915brsts880804of.jpg";
    NSURL *url = [NSURL URLWithString:fileURLString];