I have a switch called soundSwitch, I am saving the state of the button using an user default 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 defaults value is initially false when the user first launches the application.
How do I implement the defaults to be true if the user is first launching the app and it they haven't been configured yet.
I have seen methods in Objective-C, but nothing in Swift. From what I have seen you can do it in the app delegate some how, or in a plist file. How do I do either of those ones?
Using "registerDefaults" you can set Default value of NSUserDefaults
Note: write this in didFinishLaunchingWithOptions, so default value is set.
write below code where you want to check
Put this in your "didFinishLaunchingWithOptions" in your AppDelegate.
Add this to your
didFinishLaunchingWithOptions
method from the AppDelegate. As some others pointed out try not to abuse by putting everything in this method.Swift 4
I prefer to implement a function similar to UserDefaults.string(forKey: ) which returns nil if the value is not set. Combined with the ?? operator, you don't need to have any default values written to disk unless you explicitly set them later.
Then you can retrieve your default values as follows
Set and get sound activated.
Set bool value by
check bool value by
Swift 3 syntax example
Register a boolean default value:
And to get the value:
Sidenote: Although the above code will return true, note that the value isn't actually written to disk until you set it: