First, we need to ask for the user's permission to access the folder, but for that, we need an NSSavePanel
:
let op = NSSavePanel()
op.message = "Descriptive message here"
op.canCreateDirectories = false
op.canChooseDirectories = false
op.showsHiddenFiles = false
op.prompt = "Allow"
op.title = "Allow access"
op.isExtensionHidden = true
op.directoryURL = URL(string: "/path/to/folder")
// Depending on your purpose, you might need these to true
op.allowsMultipleSelection = false
op.canChooseFiles = false
We then check if the panel's URL matches the one we need, and save a secure scoped bookmark in user defaults, for example:
guard op.runModal() == .OK && openPanel.URL == requiredURL else {
return
}
guard
let bookmarkData = try? requiredURL.bookmarkData(
options: [.withSecurityScope],
includingResourceValuesForKeys: nil,
relativeTo: nil),
bookmarkData != nil
else { return }
UserDefaults.standard.set(bookmarkData, forKey: requiredURLKey)
From now on, when we need access to this location, we can just resolve the data saved back into an NSURL
, and use it; we just need to check if the bookmark staled in the meantime:
var staleBookmark = false
guard
let bookmarkData = UserDefaults.standard.data(forKey: requiredURLKey),
let url = try? URL(resolvingBookmarkData: bookmarkData,
options: [.withSecurityScope],
relativeTo: nil,
bookmarkDataIsStale: &staleBookmark)
else { return }
guard !staleBookmark else { return }
// [...] Use the URL.