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?

Maury Markowitz
  • 9,082
  • 11
  • 46
  • 98

2 Answers2

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.

pkamb
  • 33,281
  • 23
  • 160
  • 191
Adrian Sluyters
  • 2,186
  • 1
  • 16
  • 21
  • And this is what you get for assuming `NSURL.fileURLWithPath` would do expansions... *sigh* – Maury Markowitz Apr 06 '16 at 16:14
  • 2
    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. – Adrian Sluyters Apr 06 '16 at 16:16
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)
Sam Spencer
  • 8,492
  • 12
  • 76
  • 133
Yevhenii Hyzyla
  • 183
  • 4
  • 5