Skip to content

Instantly share code, notes, and snippets.

@cmittendorf
Created April 19, 2015 20:37
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save cmittendorf/a427e5ae1e390bdced9b to your computer and use it in GitHub Desktop.
Save cmittendorf/a427e5ae1e390bdced9b to your computer and use it in GitHub Desktop.
A small extension for registering NSUserDefaults default values using its registerDefaults method from the default values of a settings bundle. See http://oleb.net/blog/2014/02/nsuserdefaults-handling-default-values/ for more information on NSUserDefaults and default values. The code respects an ApplicationGroupContainerIdentifier key and uses N…
import Foundation
if let bundleURL = NSBundle.mainBundle().URLForResource("Settings", withExtension: "bundle") {
NSUserDefaults.registerDefaults(settingsBundleURL: bundleURL)
}
extension NSUserDefaults {
static func registerDefaults(#settingsBundleURL: NSURL) {
if let rootDict = NSDictionary(contentsOfURL: settingsBundleURL.URLByAppendingPathComponent("Root.plist")) {
var defaults: NSUserDefaults?
if let containerIdentifier = rootDict.valueForKey("ApplicationGroupContainerIdentifier") as? String {
defaults = NSUserDefaults(suiteName: containerIdentifier)
} else {
defaults = NSUserDefaults.standardUserDefaults()
}
if let defaults = defaults, preferences = rootDict.valueForKey("PreferenceSpecifiers") as? [[String:AnyObject]] {
var registrationDictionary: [NSObject:AnyObject] = [:]
for prefs in preferences {
if let type = prefs["Type"] as? String {
switch type {
case "PSToggleSwitchSpecifier":
if let boolValue = prefs["DefaultValue"] as? Bool, let key = prefs["Key"] as? String {
registrationDictionary[key] = boolValue
}
case "PSSliderSpecifier":
if let floatValue = prefs["DefaultValue"] as? Float, let key = prefs["Key"] as? String {
registrationDictionary[key] = floatValue
}
case "PSTextFieldSpecifier", "PSMultiValueSpecifier":
if let textValue = prefs["DefaultValue"] as? String, let key = prefs["Key"] as? String {
registrationDictionary[key] = textValue
}
default:
continue
}
}
}
defaults.registerDefaults(registrationDictionary)
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment