User has to save a file, but I only want them saving the file in one folder. How to do this?
I have already tried implementing the delegate and forcefully setting back the directory if it is different. This does not work. The user is still able to select other folders when the save panel opens
extension Project: NSOpenSavePanelDelegate {
func panel(_ sender: Any, didChangeToDirectoryURL url: URL?) {
if url != testsFolder {
(sender as! NSSavePanel).directoryURL = testsFolder
}
}
func panel(_ sender: Any, validate url: URL) throws {
if url.deletingLastPathComponent() != testsFolder {
(sender as! NSSavePanel).directoryURL = testsFolder
throw ProjectError.scriptInitiliation
}
}
}
The thing is, the folder is already fix fixed within the app.
This is the time to acquire permission from the user to access this folder. Use a open (not save) dialog to have the user confirm selection of the folder. Think of this as a "confirm access dialog", you can:
prompt
title
and message
so the dialog is clearly a confirmation dialogdirectoryURL
to the parent of the one you want confirmed (Note: any changes to directoryURL
after the dialog is up are ignored so you cannot lock the dialog to that folder using the delegate didChangeToDirectoryURL
– in the early sandbox you could but Apple has now stopped that)delegate
and use its shouldEnable
and validate
callbacks to make sure only the folder you wish to have confirmed can be selected or the dialog cancelled.canCreateDirectories
& canChooseFiles
to false
, canChooseDirectories
to true
Once the user has confirmed the folder access save a security scoped bookmark in your app's prefs. Your app can now regain access to that folder at any time. With that permission you can create and open files and folders within that folder without using NSOpenPanel
or NSSavePanel
again.
From this point to restrict users to saving in that folder put up your own dialog to ask for just the filename, omitting the path part, and bypass NSSavePanel
–you can impersonate the standard dialogs or design your own from scratch.
HTH