When the user clicks a button in my application I want to have the Finder come to the front and display the contents of a folder. The NSWorkspace
class has two calls, activateFileViewerSelectingURLs(:)
and selectFile(:inFileViewerRootedAtPath:)
, that almost do what I want, but they both select one or more items. I don't want the Finder to select anything.
I see the behavior I want if I enter
/usr/bin/open /path/to/my/folder
in Terminal. Is there a Cocoa API for doing this, or do I need to have NSTask
run /usr/bin/open
?
It suffices to ask the workspace to open the folder as a file, because the Finder is the default app for folders. For example:
NSWorkspace.shared.open(
URL(
fileURLWithPath: "/System/Library/CoreServices",
isDirectory: true
)
)
(The isDirectory
parameter is optional but passing it saves a system call.)
If you want to be sure to have the Finder open the folder regardless of the default app settings, you could use Applescript:
NSString *script = [NSString StringWithFormat:
@“tell application \”Finder\”\nopen folder (\“%@\” as POSIX file)\nend tell\n”, path];
NSAppleScript *openScript = [[NSAppleScript alloc] initWithSource: script];
[openScript executeAndReturnError:nil];
AppleScript was a solution for me, but I had to add tabs (\t
) for it to work:
NSString* path = ...;
NSString* script = [NSString stringWithFormat:@"tell application \"Finder\"\n\tactivate\n\tmake new Finder window to (POSIX file \"%@\")\nend tell\n", path];
NSAppleScript* openScript = [[NSAppleScript alloc] initWithSource:script];
[openScript executeAndReturnError:nil];
so that resulting script looks like:
tell application "Finder"
activate
make new Finder window to (POSIX file "/Users/MyUser/someFolder")
end tell
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With