Reputation: 3
I am creating a small program that will help automate the initialization of a virtual environment and startup of a Django server. I would like to share this program with others.
I am looking for a way to create a variable (location of a folder) through the use of an open file browser and store that variable so that the user does not have to enter it in the future.
How can I store new information in my program for future use? I investigated the use of the plist file but cant find any documentation anywhere. Thanks for your help!
Upvotes: 0
Views: 691
Reputation: 923
You can persistently store simple values in the user's preferences by using the NSUserDefaults class from Cocoa.
The following script asks the user to choose a folder location the first time it is run and then stores the chosen location in the user's defaults. When the script is run again, it returns the stored location without prompting the user. (Change the suiteName
and locationKey
values as appropriate for your script.)
var currentApp = Application.currentApplication()
currentApp.includeStandardAdditions = true
var suiteName = "your.suite.name";
var locationKey = "your.prefs.key";
var $ud = $.NSUserDefaults.alloc.initWithSuiteName(suiteName);
var $location = $ud.stringForKey(locationKey);
var locationPath = $location.isNil() ? currentApp.chooseFolder() : Path($location.js);
$ud.setObjectForKey($(locationPath.toString()), locationKey);
locationPath
Note that you can also interact with the user's preferences using the defaults
command-line tool, e.g.:
defaults read your.suite.name your.prefs.key
defaults delete your.suite.name your.prefs.key
Upvotes: 1
Reputation: 1807
I suggested using plist above, but I just ran across this great tool: JSON Helper
It is a app that supports scripting. The examples are shown in AppleScript, but should be easily translated to JXA.
JSON Helper is an agent (or scriptable background application) which allows you to do useful things with JSON (JavaScript Object Notation) directly from AppleScript. JSON Helper has no interface, and runs in the background waiting for AppleScripts [or JXA] to ask it to do something, just like Apple's own System Events does.
JSON Helper contains a number of commands that help you parse JSON into regular AppleScript lists and records, and convert AppleScript list and records back into valid JSON. In addition JSON Helper contains some convenience commands to allow you to communicate easily with web based APIs.
Upvotes: 0