R.Ham R.Ham - 1 month ago 13
Swift Question

Swift: User default values not being saved/ loaded when app is opened and closed

I have a global settings variable (SettingsVariable.settingOne) that is changed by the user during the apps runtime. I want to make the users change permanent, but at the moment every time the app is then reloaded it reverts to the original values e.g. user changes value to false, but then when the app is rerun the variables value changes back to the original value.

When the value is changed the following code is called (swift 2):

NSUserDefaults.standardUserDefaults().setBool(false, forKey: "settingOne")


and when the app is closed:

func applicationWillTerminate(application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.

NSUserDefaults.standardUserDefaults().setBool(SettingsVariables.settingOne, forKey: "settingOne")
}


then once the app is opened again:

func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.

NSUserDefaults.standardUserDefaults().boolForKey("settingOne")

return true
}


But the value of settingOne keeps reverting back to the default value of 'true' set originally within the application.

SettingsVariables.settingOne is contained within a struct:

import UIKit

struct SettingsVariables {

static var settingOne = true

}

Answer

You need to give synchronize to save NSUserDefaults.

So your code must be

func applicationWillTerminate(application: UIApplication) {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.

    NSUserDefaults.standardUserDefaults().setBool(SettingsVariables.settingOne, forKey: "settingOne")
    NSUserDefaults.standardUserDefaults().synchronize()
}
Comments