Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NSOpenPanel choose a directory ( not a file)

I want to let user to choose a directory for saving a file. but how to make sure the url is a directory not a file?

NSOpenPanel* panel = [NSOpenPanel openPanel];
[panel setCanChooseDirectories:YES];
[panel setCanCreateDirectories:YES];

[panel beginSheetModalForWindow:self.window completionHandler:^(NSInteger result){
    if (result == NSFileHandlingPanelOKButton) {
        NSArray* urls = [panel URLs];
        for (NSURL *url in urls) {
            //here how to judge the url is a directory or a file
        }
    }
}];
like image 261
Mil0R3 Avatar asked Jul 18 '12 07:07

Mil0R3


3 Answers

Update for anyone reading this in the future:

In Swift, checking if the picked path is a file can be avoided by using

panel.canChooseFiles = false
like image 194
Kendrick Ledet Avatar answered Oct 23 '22 21:10

Kendrick Ledet


// First, check if the URL is a file URL, as opposed to a web address, etc.
if (url.isFileURL) {
  BOOL isDir = NO;
  // Verify that the file exists 
  // and is indeed a directory (isDirectory is an out parameter)
  if ([[NSFileManager defaultManager] fileExistsAtPath: url.path isDirectory: &isDir]
      && isDir) {
    // Here you can be certain the url exists and is a directory
  }
}
like image 6
waldrumpus Avatar answered Oct 23 '22 19:10

waldrumpus


Swift 4 version:

if (url.isFileURL) {
    var isDir: ObjCBool = false
    if (FileManager.default.fileExists(atPath: url.path, isDirectory: &isDir)) { 
       if isDir.boolValue {
                            print("It's a Directory path")
                          } else {
                            print("It's a file path")
                        }
                    }
}
like image 1
Francis F Avatar answered Oct 23 '22 20:10

Francis F