Search code examples
swift3macos-sierra

Open directory in finder?


I'm trying to open a directory in a finder window. I have the following code, but it does not display the contents of the inspirations directory - instead, it highlights the inspirations directory.

I have included a trailing slash, so I'm not sure why it isn't opening the directory?

let apppath: String = "/Applications/Inspirations/"

    // OPEN THE DIRECTORY IN THE FINDER
   NSWorkspace.shared().activateFileViewerSelecting([NSURL].init(arrayLiteral: NSURL.init(fileURLWithPath: apppath)) as [URL])

Can someone please advise me how I get the finder window to display the files inside the inspirations directory?

Thank you all in advance.


Solution

  • You should use FileManager urls for applicationDirectory at the systemDomainMask and append your path component to the url returned. Then all you need is use open method and pass your directory url:

    if let inspirationsDirectory = FileManager.default.urls(for: .applicationDirectory, in: .systemDomainMask).first?.appendingPathComponent("Inspirations", isDirectory: true){
        NSWorkspace.shared.open(inspirationsDirectory)
    }