问题
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
}
}
}
回答1:
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:
- Change the label of the "Open" button to something else using
prompt
- Set the
title
andmessage
so the dialog is clearly a confirmation dialog - set the initial folder using
directoryURL
to the parent of the one you want confirmed (Note: any changes todirectoryURL
after the dialog is up are ignored so you cannot lock the dialog to that folder using the delegatedidChangeToDirectoryURL
– in the early sandbox you could but Apple has now stopped that) - Set the
delegate
and use itsshouldEnable
andvalidate
callbacks to make sure only the folder you wish to have confirmed can be selected or the dialog cancelled. - Set
canCreateDirectories
&canChooseFiles
tofalse
,canChooseDirectories
totrue
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
来源:https://stackoverflow.com/questions/58550993/nssavepannel-how-to-restrict-user-to-only-save-one-one-set-directory