2012-07-18 4 views
9

Я хочу, чтобы пользователь мог выбрать каталог для сохранения файла. но как убедиться, что url - это каталог, а не файл?NSOpenPanel выбрать каталог (а не файл)

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

ответ

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

Update для тех, кто читает это в будущем:

В Swift, проверка, если выбрал путь файла можно избежать с помощью

panel.canChooseFiles = false 
+0

Технически, который работает на Objective -C тоже, хотя я бы использовал 'NO' вместо' false'. –

+0

Да, это правда, но в Swift вы должны использовать false. –

Смежные вопросы