I have an application that uses the app Defaults to store a boolean value to indicate whether in-app sounds should be audible or not as an app preference. This can be managed with a toggle in settings.
However, when the app is freshly installed, the default is not set and the value is false. However, I want it to be true by default.
On appear of the root of the app I tried something like this, however the value is not registered in the preference .plist of the app. What am I doing wrong?
if UserDefaults.standard.object(forKey: "Music") == nil {
UserDefaults.standard.set(true, forKey: "Music")
}
Also, in the View where I use the default value and have placed the toggle switch, I use
@AppStorage("Music") private var music: Bool = true
I thought that when the Music app preference value was not set, it would use true to initialise it. It does not seem to do any of that. Only when the toggle is hit, it sets and updates the value in .plist.
In the root of your app or the entry point of your app's launch, check if the "Music" key exists in the UserDefaults. If it doesn't exist, set the initial value using the @AppStorage property wrapper. For example:
Note: By doing this, the initial value for the "Music" preference will be set to true only when the "Music" key is not found in UserDefaults. Subsequently, the @AppStorage property wrapper will handle the syncing of the preference value between the UserDefaults and your music property. Make sure you only set the default value once when the app is launched, to avoid overwriting user changes to the preference. Verify that you are correctly retrieving and updating the music property. If the preference value is not being set correctly, it may be due to a different issue in your code. Double-check the code where you access and modify the music property to ensure it is being used consistently.
If you are using a toggle switch to modify the music property, ensure that the binding is properly set up. The toggle switch should be bound to the music property using @AppStorage:
Check if there are any other places in your code where the "Music" preference value is being modified or overwritten. It's possible that there might be conflicting code or logic that is causing the value to not persist as expected.