swiftnsopenpanelnssavepanel

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


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
        }
    }
}

Solution

  • 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:

    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