Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
// https://stackoverflow.com/questions/42179567/what-does-startaccessingsecurityscopedresource-actually-do/49196035?noredirect=1#comment85430898_49196035
// - Create ViewController with 3 Buttons
// - Enable App Sandbox User Selected File Read/Write
// - Click Button1, select folder /tmp/
// - Restart app, press Button3 -> crash
// - Restart app, press Button2 and Button3 -> works
import Cocoa
class ViewController: NSViewController {
override func viewDidLoad() {
super.viewDidLoad()
}
@IBAction func pressButton(_ sender: AnyObject) {
let panel = NSOpenPanel()
panel.canChooseDirectories = true
panel.canChooseFiles = false
panel.prompt = "Select /tmp"
guard panel.runModal() == NSApplication.ModalResponse.OK else { return }
guard let url = panel.url else { return }
NSLog("%@", "\(url.absoluteString)")
let data = try! url.bookmarkData(options: .withSecurityScope, includingResourceValuesForKeys: nil, relativeTo: nil)
UserDefaults.standard.set(data, forKey: "bookmark")
NSLog("bookmark stored")
}
@IBAction func pressButton2(_ sender: AnyObject) {
let data = UserDefaults.standard.data(forKey: "bookmark")!
var bookmarkDataIsStale: ObjCBool = false
let url = try! (NSURL(resolvingBookmarkData: data, options: [.withoutUI, .withSecurityScope], relativeTo: nil, bookmarkDataIsStale: &bookmarkDataIsStale) as URL)
if bookmarkDataIsStale.boolValue {
NSLog("WARNING stale security bookmark")
return
}
if !url.startAccessingSecurityScopedResource() {
NSLog("startAccessingSecurityScopedResource FAILED")
}
NSLog("startAccessing done")
}
@IBAction func pressButton3(_ sender: AnyObject) {
let text = "just a test"
let fileURL = URL(fileURLWithPath: "/tmp/file.txt")
try! text.write(to: fileURL, atomically: false, encoding: .utf8)
let text2 = try! String(contentsOf: fileURL, encoding: .utf8)
NSLog("READ: \(text2)")
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment