retrieving the value of Toggle Switch from Settings.bundle with Swift 5

Viewed 407

enter image description here

let sfx : Bool = UserDefaults.standard.bool(forKey: SettingsBundleKeys.SFX)

Whenever the code runs. the value being retrieved is always false. As you can see in the image, the default value is YES (on application first install, it should be true until the user changes it to NO)

struct SettingsBundleKeys {
    static let Reset = "RESET_APP_KEY"
    static let Music = "MUSIC_PREFERENCE"
    static let SFX = "SFX_PREFERENCE"
    static let BuildVersionKey = "build_preference"
    static let AppVersionKey = "version_preference"
}
1 Answers

When using a settings bundle:

The "default value"s in the settings bundle are only used by the iOS Settings app and never by your app. The "default value for a toggle switch" is saying show the toggle as ON if there is no userDefault (either YES or NO) set yet.

You need to do something in your own app so that if the user hasn't chosen a default value for this key you treat it also as YES so that it matches the 'default default value' in the settings bundle.

One possibility would be that instead of

let sfx: Bool = UserDefaults.standard.bool(forKey: SettingsBundleKeys.SFX)

you could use objectForKey, which would return nil, and then you would know to use the 'default default' and could behave as if YES has been set as the value. (This kind of thing could be achieved using a property wrapper on user defaults) but what Apple say is:

Call UserDefault's registerDefaults from application:didFinishLaunchingWithOptions:

That way your app and the settings app are in sync with respect to the 'default defaults' - values to be used for keys for which no user default has been registered - and then bool(forKey: SettingsBundleKeys.SFX) would return YES even if no user default has yet been set for the SFX key

Related