Skip to content

Instantly share code, notes, and snippets.

@dnicolson
Created April 24, 2021 20:30
Show Gist options
  • Save dnicolson/7fe244212dd12f34def446878b4ff1ae to your computer and use it in GitHub Desktop.
Save dnicolson/7fe244212dd12f34def446878b4ff1ae to your computer and use it in GitHub Desktop.
Read the home directory in a sandboxed app by calling NSOpenPanel
import Cocoa
import Foundation
class ViewController: NSViewController {
private func promptForWorkingDirectoryPermission() -> URL? {
let openPanel = NSOpenPanel()
openPanel.message = "Choose home directory"
openPanel.prompt = "Choose"
openPanel.allowedFileTypes = ["none"]
openPanel.allowsOtherFileTypes = false
openPanel.canChooseFiles = false
openPanel.canChooseDirectories = true
_ = openPanel.runModal()
return openPanel.urls.first
}
override func viewDidLoad() {
super.viewDidLoad()
let url = promptForWorkingDirectoryPermission()
let fileManager = FileManager.default
do {
let contents = try fileManager.contentsOfDirectory(at: url!, includingPropertiesForKeys: nil)
for content in contents {
print(content)
}
} catch {
print(error)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment