DISCLAIMER: This post is older than one year and maybe out of date.

Saving user settings with userDefaults on macOS using Swift

I have been working more on my macOS blogging application. You may recall it builds GatsbyJS compatible markdown files for me to easily post to CompileSwift.com and PeterWitham.com

The focus for this week was adding the ability to set a default path to save the files without having to set it every time I want to save a new file. This requires using NSOpenPanel to display a standard macOS file opener panel, however I have disabled the file selection and enabled the path selection using the following

let pathSelector = NSOpenPanel()
pathSelector.canChooseFiles = false
pathSelector.canChooseDirectories = true

This enables me to use only the path selection which is all I need for setting the location in userDefaults. I am using userDefaults since I only intend to store small amounts of data for the application preferences and this will do just nicely with very little code.

There are a couple of other tweaks I made to the panel for setting the path

// Set the title of the window
pathSelector.title = "Select a location to save files to"
// Set the button label, by default it says 'Open'
pathSelector.prompt = "Set Path"
// Set the path to open in the dialog if one exists in
// userDefaults already
pathSelector.directoryURL = defaults.url(forKey: "savePath")

If the ‘Set Path’ button is clicked then it will save the new path in userDefaults and update the displayed path. If ‘Cancel’ is clicked then the current path is retained, if one exists in the settings.

I feel this is a pretty straight forward and simple solution to the problem.