2012-07-18 13 views
9

Quiero permitir que el usuario elija un directorio para guardar un archivo. pero, ¿cómo asegurarse de que la URL es un directorio, no un archivo?NSOpenPanel elegir un directorio (no un archivo)

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

Respuesta

7
// 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 
    } 
} 
15

Actualización para cualquiera que lea esto en el futuro:

En Swift, comprobando si el camino elegido es un archivo se puede evitar mediante el uso de

panel.canChooseFiles = false 
+0

Técnicamente que trabaja para el objetivo -C también, aunque usaría 'NO' en lugar de' false'. –

+0

Sí, eso es cierto, pero en Swift debes usar falso. –

Cuestiones relacionadas