Question

I have the user select a folder from an NSOpenPanel. This returns a filepath like: file://localhost/Folder. Here is my code where it all goes wrong:

NSURL *filePath = [openDlg URL]; //OpenDlg is my NSOpenPanel
NSString *s = [filePath absoluteString];
NSLog(@"%@",s);
NSError *error;
NSArray *b = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:s error:&error];
if (error) {
    NSLog(@"%@",error);
}
NSLog(@"%lu",b.count);

Here, no matter what folder I select, this error message is sent: The folder “Folder” doesn’t exist." UserInfo=0x10518b320 {NSFilePath=file://localhost/Folder, NSUserStringVariant=( Folder ), NSUnderlyingError=0x10515d5e0 "The operation couldn’t be completed. (OSStatus error -43.)"}

What is going on?!? If this isn't the best way to do it how can I access all the files inside of a folder?

Was it helpful?

Solution

Try using this method instead:

- (NSArray *)contentsOfDirectoryAtURL:(NSURL *)url includingPropertiesForKeys:(NSArray *)keys options:(NSDirectoryEnumerationOptions)mask error:(NSError **)error

You can just pass in the NSURL without having to convert it into a NSString. To give you an example of how you would use it, see below:

[[NSFileManager defaultManager] contentsOfDirectoryAtURL:filePathURL 
                              includingPropertiesForKeys:[NSArray arrayWithObjects:NSURLNameKey, nil]
                                                 options:NSDirectoryEnumerationSkipsHiddenFiles 
                                                   error:&error];

I can't see how you setup your NSOpenPanel so I will also include an example of how to set that up below:

NSOpenPanel *openPanel = [NSOpenPanel openPanel];

[openPanel beginSheetModalForWindow:self.window completionHandler:^(NSInteger result){

        if (result == NSFileHandlingPanelOKButton) {
            NSArray* urls = [openPanel URLs];

            NSURL *url = [urls objectAtIndex:0];
            if (url != nil) {

                // If you want to convert the path to a NSString
                self.filePathString = [url path];
                // If you want to keep the path as a NSURL
                self.filePathURL = url;

            }

        }

    }];

The above method will get the path to the file or folder after the user has pressed the OK button. Give that a try and see if it works. To further elaborate on why I suggested you use NSURL, here is the explanation that the Apple Documentation gives:

The preferred way to specify the location of a file or directory is to use the NSURL class. Although the NSString class has many methods related to path creation, URLs offer a more robust way to locate files and directories. For applications that also work with network resources, URLs also mean that you can use one type of object to manage items located on a local file system or on a network server.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top