16

I have a NSOpenPanel. But I want to make it PDF-files selectable only. I'm looking for something like that:

// NOT WORKING 
NSOpenPanel *panel;

panel = [NSOpenPanel openPanel];
[panel setFloatingPanel:YES];
[panel setCanChooseDirectories:YES];
[panel setCanChooseFiles:YES];
[panel setAllowsMultipleSelection:YES];
[panel setAllowedFileTypes:[NSArray arrayWithObject:@"pdf"]];
int i = [panel runModalForTypes:nil];
if(i == NSOKButton){
    return [panel filenames];
}

I hope someboby has a solution.

Andreas Prang
  • 2,187
  • 4
  • 22
  • 33

2 Answers2

34

A couple things I noticed.. change setCanChooseDirectoriesto NO. When enabled this indicates that folders are valid input. This is most likely not the functionality you want. You might also want to change your allowed file types to [NSArray arrayWithObject:@"pdf", @"PDF", nil] for case sensitive systems. runModalForTypes should be the array of file types. Change your code to look like this:

// WORKING :)
NSOpenPanel *panel;
NSArray* fileTypes = [NSArray arrayWithObjects:@"pdf", @"PDF", nil];
panel = [NSOpenPanel openPanel];
[panel setFloatingPanel:YES];
[panel setCanChooseDirectories:NO];
[panel setCanChooseFiles:YES];
[panel setAllowsMultipleSelection:YES];
[panel setAllowedFileTypes:fileTypes];
int i = [panel runModal];
if(i == NSOKButton){
    return [panel URLs];
}

Swift 4.2:

let fileTypes = ["jpg", "png", "jpeg"]
let panel = NSOpenPanel()
panel.canChooseFiles = true
panel.canChooseDirectories = false
panel.allowsMultipleSelection = false
panel.allowedFileTypes = fileTypes
panel.beginSheetModal(for: window) { (result) in
    if result.rawValue == NSApplication.ModalResponse.OK.rawValue {
         // Do something with the result.
         let selectedFolder = panel.urls[0]
         print(selectedFolder)
    }
}
Justin Meiners
  • 10,754
  • 6
  • 50
  • 92
  • Doesn't this leak fileTypes? – M Katz Feb 06 '17 at 01:36
  • @MKatz thank you for the catch. Without ARC alloc must be followed by release. I will change it to arrayWithObjects: – Justin Meiners Feb 07 '17 at 02:37
  • This doesn't work although no errors are generated. The file selection window opens but all file types are displayed and can be selected normally....using Swift 5 on MacOS Mojave 10.14.5 XCode 11 Beta – Heitor Jun 09 '19 at 04:18
  • 1
    `panel.allowedFileTypes = [NSImage imageTypes];` (obj-c syntax) to get all image types supported by `NSImage`. – wcochran Dec 22 '21 at 17:08
2

You are very close to the answer.

First, get rid of [panel setCanChooseDirectories:YES] so that it won't allow directories as a result.

Then, either change[panel runModalForTypes:nil] to [panel runModal] or get rid of the call to [panel setAllowedFileTypes:] and pass the array to [panel runModalForTypes:] instead.

Sangram Shivankar
  • 3,535
  • 3
  • 26
  • 38
ughoavgfhw
  • 39,734
  • 6
  • 101
  • 123