2012-07-18 19 views
9

Voglio consentire all'utente di scegliere una directory per salvare un file. ma come assicurarsi che l'url sia una directory e non un file?NSOpenPanel sceglie una directory (non un 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 
     } 
    } 
}]; 

risposta

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

Aggiornamento per chiunque legga questo in futuro:

In Swift, controllando se il percorso scelto è un file può essere evitato utilizzando

panel.canChooseFiles = false 
+0

Tecnicamente che funziona per l'obiettivo -C anche se userei 'NO' invece di' false'. –

+0

Sì, è vero, ma in Swift dovresti usare false. –

Problemi correlati