Search code examples
swiftdirectoryfindernsworkspace

Show folder's contents in finder using Swift


I want to be able to select a folder and show its contents in the Finder. I have managed to select the folder itself and select a file within the folder. But I don't know how to show the contents of an empty folder.

e.g.

Folder A/Folder B

I want to display the contents of folder Folder B (which could be empty).

I have written the following code:

func showFolder(fileName : String)
{
    var dataPath = homeDirectory.stringByAppendingPathComponent(fileName)
    var urlPath = NSURL(fileURLWithPath: dataPath)
    var selectedURLs = [urlPath!]
    NSWorkspace.sharedWorkspace().activateFileViewerSelectingURLs(selectedURLs)
}

This only opens Folder A with Folder B highlighted. This is very close, but not quite right.

I need to be able to open Folder B with nothing highlighted. I'm obviously using the wrong command.


Solution

  • Use the selectFile method and pass nil as first argument and the path to the folder to be shown as second argument.

    NSWorkspace.shared.selectFile(nil, inFileViewerRootedAtPath: "/Users/")