I have a switch called soundSwitch
, I'm saving the state of the button using an userDefault
as such:
@IBAction func soundsChanged(sender: AnyObject) { if soundSwitch.on{ defaults.setBool(true, forKey: "SoundActive") print("Sound ON") }else{ defaults.setBool(false, forKey: "SoundActive") print("Sound OFF") } }
Currently, the actual default value is initially false when the user first launches the application.
How can I implement the defaults to be true if the user launches the app and they haven't been configured yet.
I've seen methods in Objective-C
, but nothing in Swift. From what I've seen you can do it in the app delegate somehow, or in a PList
file. How do I do either of those ones?
It appears the limit is the maximum file size for iOS (logically), which is currently 4GB: https://discussions.apple.com/thread/1763096?tstart=0. The precise size of the data is circumscribed by the compiler types (NSData, NSString, etc.) or the files in your asset bundle.
All the contents saved by NSUserDefaults is saved inside a plist file that can be found under Library -> Preferences -> $AppBundleId. plist as shown in the image below. Open up the plist file and you can easily view the contents of the file.
Overview. The NSUserDefaults class provides a programmatic interface for interacting with the defaults system. The defaults system allows an app to customize its behavior to match a user's preferences. For example, you can allow users to specify their preferred units of measurement or media playback speed.
Because NSUserDefaults stores all data in an unencrypted . plist file, a curious person could potentially view this data with minimal effort. That means that you should never store any type of sensitive data inside NSUserDefaults.
Swift 3 syntax example
Register a boolean default value:
UserDefaults.standard.register(defaults: ["SoundActive" : true])
And to get the value:
UserDefaults.standard.bool(forKey: "SoundActive")
Sidenote: Although the above code will return true, note that the value isn't actually written to disk until you set it:
UserDefaults.standard.set(true, forKey: "SoundActive")
Add this to your didFinishLaunchingWithOptions
method from the AppDelegate. As some others pointed out try not to abuse by putting everything in this method.
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { /// Here you can give default values to your UserDefault keys UserDefaults.standard.register(defaults: [ "SoundActive": true, "someOtherKey": "Some Message" ]) }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With