Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NSOpenPanel's setDirectoryURL doesn't work

I'm trying to use the new methods for NSOpenPanel and set its initial directory. The problem is that it only works at the first time and after that it just "remembers" the last selected folder, which I don't want. I have to use the depreciated runModalForDirectory:file: to make it work. It's less than ideal because it was deprecated at 10.6, but thankfully it still works on Lion.

My code is:

NSOpenPanel *panel = [NSOpenPanel openPanel];
[panel setAllowedFileTypes:[NSArray arrayWithObjects: @"jpg",@"JPG",@"png", nil]];
panel.canChooseDirectories = YES;
panel.allowsMultipleSelection = YES;
handler = ^(NSInteger result) {stuff};
[panel setDirectoryURL:[NSURL URLWithString:@"/Library/Desktop Pictures"]];
like image 981
Tibidabo Avatar asked Dec 22 '22 07:12

Tibidabo


2 Answers

There are a couple things to look into:

  1. ~/Pictures is not a valid URL. file:///Users/user/Pictures is. -[NSURL URLWithString:] requires a valid URL. You probably want to use -[NSURL fileURLWithPath:] instead. It will turn /Users/user/Pictures into file:///Users/user/Pictures.
  2. Tildes are not automatically expanded, so you want to use [@"~/Pictures stringByExpandingTildeInPath] to get an actual file path.

Put together, change the last line to:

[panel setDirectoryURL:[NSURL fileURLWithPath:[@"~/Pictures" stringByExpandingTildeInPath]]];

I think that should work.

like image 161
mipadi Avatar answered Jan 20 '23 10:01

mipadi


The panel in Lion expects an URL like: file://localhost/Library/Desktop Pictures, but your URL starts with the actual path. Use [NSURL fileURLWithPath:@"/Library/Desktop Pictures"] instead.

Happy coding!

like image 41
Helge Becker Avatar answered Jan 20 '23 11:01

Helge Becker