23

In my application I would like to create a 'Show in Finder' button.

Show in Finder in Xcode

I have been able to figure out how to pop up a Finder window of that directory but haven't figured out how to highlight the file like the OS does.

Is this possible?

pkamb
  • 33,281
  • 23
  • 160
  • 191
Locksleyu
  • 5,192
  • 8
  • 52
  • 77
  • "how to pop up a finder window of that directory"? – onmyway133 Aug 23 '14 at 14:40
  • Possible duplicate of [Launch OSX Finder window with specific files selected](http://stackoverflow.com/questions/7652928/launch-osx-finder-window-with-specific-files-selected) – eonil May 25 '16 at 12:56

4 Answers4

42
NSArray *fileURLs = [NSArray arrayWithObjects:fileURL1, /* ... */ nil];
[[NSWorkspace sharedWorkspace] activateFileViewerSelectingURLs:fileURLs];

stolen from Launch OSX Finder window with specific files selected

Community
  • 1
  • 1
owen gerig
  • 6,165
  • 6
  • 52
  • 91
15

You can use NSWorkspace method -selectFile:inFileViewerRootedAtPath: like this:

[[NSWorkspace sharedWorkspace] selectFile:fullPathString inFileViewerRootedAtPath:pathString];
Justin Boo
  • 10,132
  • 8
  • 50
  • 71
3

Its worth mentioning that owen's method only works from osx 10.6 or later (Ref: https://developer.apple.com/library/mac/#documentation/Cocoa/Reference/ApplicationKit/Classes/NSWorkspace_Class/Reference/Reference.html ).

So if your writing something to run on the older generations its probably better to do it in the way suggested by justin as its not been deprecated (yet).

andrewktmeikle
  • 477
  • 5
  • 16
0
// Place the following code within your Document subclass

// enable or disable the menu item called "Show in Finder"
override func validateUserInterfaceItem(anItem: NSValidatedUserInterfaceItem) -> Bool {
    if anItem.action() == #selector(showInFinder) {
        return self.fileURL?.path != nil;
    } else {
        return super.validateUserInterfaceItem(anItem)
    }
}

// action for the "Show in Finder" menu item, etc.
@IBAction func showInFinder(sender: AnyObject) {

    func showError() {
        let alert = NSAlert()
        alert.messageText = "Error"
        alert.informativeText = "Sorry, the document couldn't be shown in the Finder."
        alert.runModal()
    }

    // if the path isn't known, then show an error
    let path = self.fileURL?.path
    guard path != nil else {
        showError()
        return
    }

    // try to select the file in the Finder
    let workspace = NSWorkspace.sharedWorkspace()
    let selected = workspace.selectFile(path!, inFileViewerRootedAtPath: "")
    if !selected {
        showError()
    }

}
Kaydell
  • 484
  • 1
  • 4
  • 14