7

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?

1
  • 4
    I strongly assume that you have to expand the tilde to the actual path ... Commented Apr 5, 2016 at 21:05

2 Answers 2

13

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.

Sign up to request clarification or add additional context in comments.

2 Comments

And this is what you get for assuming NSURL.fileURLWithPath would do expansions... sigh
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.
5

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.