11

我想让用户选择一个目录来保存文件。但是如何确保 url 是目录而不是文件?

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

3 回答 3

27

为将来阅读此内容的任何人更新:

在 Swift 中,可以通过使用来避免检查选择的路径是否为文件

panel.canChooseFiles = false
于 2014-06-08T22:07:00.200 回答
6
// 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
  }
}
于 2012-07-18T08:59:04.313 回答
1

斯威夫特 4版本:

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")
                        }
                    }
}
于 2018-10-10T06:24:56.053 回答