swiftmacosnsopenpanel

Setting initial directory for NSOpenPanel


I'm trying to get the user to select a file from a folder containing log files. So I want to display an NSOpenDialog showing the contents of that folder. I'm using Swift, so 10.9+

I see a number of threads on this topic here, but in spite of trying what appears to be the same code converted to Swift, it invariably returns to the Documents folder. Here's a sample:

    let fd: NSOpenPanel = NSOpenPanel()
    fd.directoryURL = NSURL.fileURLWithPath("~/LauncherLogs", isDirectory: true)
    fd.canChooseDirectories = false
    fd.canChooseFiles = true
    fd.allowedFileTypes = ["log"]
    fd.runModal()

The folder in question does exist, and copy and pasting the path into the Go to Folder... in the Finder goes right there. Any ideas?


Solution

  • You need to expand the tilde and NSString has a hand method for this so:

    let launcherLogPathWithTilde = "~/LauncherLogs" as NSString
    let expandedLauncherLogPath = launcherLogPathWithTilde.stringByExpandingTildeInPath
    fd.directoryURL = NSURL.fileURLWithPath(expandedLauncherLogPath, isDirectory: true)
    

    +1 upvote for Martin for mentioning it.