Setting initial directory for NSOpenPanel
Asked Answered
S

2

6

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?

Sidoon answered 5/4, 2016 at 21:0 Comment(1)
I strongly assume that you have to expand the tilde to the actual path ...Closefisted
T
12

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.

Tallinn answered 5/4, 2016 at 21:18 Comment(2)
And this is what you get for assuming NSURL.fileURLWithPath would do expansions... sighSidoon
I remember banging my head against the wall with this too! As user friendly apple devices and systems are, they certainly aren't developer friendly and if at best, extremely abstract.Tallinn
V
4

2022 version of approved answer:

  • .stringByExpandingTildeInPath.expandingTildeInPath
  • .file.fileURL
let dialog = NSOpenPanel();
let launcherLogPathWithTilde = "~/LauncherLogs" as NSString
let expandedLauncherLogPath = launcherLogPathWithTilde.expandingTildeInPath
dialog.directoryURL = NSURL.fileURL(withPath: expandedLauncherLogPath, isDirectory: true)
Varicotomy answered 31/7, 2022 at 9:41 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.