How to programmatically open a folder in Finder without selecting anything?

When a user clicks a button in my application, I want the Finder to come to the fore and display the contents of the folder. The class NSWorkspacehas two calls activateFileViewerSelectingURLs(:)and selectFile(:inFileViewerRootedAtPath:)that almost do what I want, but both of them select one or more elements. I don’t want Finder to choose anything.

I see the behavior that I want if I introduce

/usr/bin/open /path/to/my/folder

in the terminal. Is there a Cocoa API for this, or do I need to have NSTaskrun /usr/bin/open?

+4
source share
3 answers

, Finder :

NSWorkspace.sharedWorkspace().openFile("/path/to/my/folder")
+9

, Finder , 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];
+1

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 the result of the script is as follows:

tell application "Finder"
    activate
    make new Finder window to (POSIX file "/Users/MyUser/someFolder")
end tell
0
source