Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I programmatically open a folder in the Finder without selecting anything?

Tags:

macos

cocoa

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?

like image 594
Jim Matthews Avatar asked Mar 04 '16 22:03

Jim Matthews


3 Answers

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.)

like image 97
rob mayoff Avatar answered Nov 07 '22 15:11

rob mayoff


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];
like image 40
Leland Wallace Avatar answered Nov 07 '22 16:11

Leland Wallace


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
like image 1
mixtly87 Avatar answered Nov 07 '22 15:11

mixtly87