NSSavePannel - how to restrict user to only save one one set directory?

空扰寡人 提交于 2019-12-13 03:02:39

问题


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 and message 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 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)
  • Set the 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.
  • Set 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



来源:https://stackoverflow.com/questions/58550993/nssavepannel-how-to-restrict-user-to-only-save-one-one-set-directory

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!