I use a set of general functions that get values from the defaults, and return a fallback value if the defaults couldn't be read. It's helpful to abstract this out so you can change the way you store such data in future and only need to change these functions, not everywhere you currently access defaults.
func defaultsGetBool(forKey key: String, withFallback fallback: Bool) -> Bool {
guard let value = UserDefaults(suiteName: kAppGroup)?.object(forKey: key) else { return fallback }
return value as? Bool ?? fallback
}
func defaultsGetDate(forKey key: String, withFallback fallback: Date) -> Date {
guard let value = UserDefaults(suiteName: kAppGroup)?.object(forKey: key) else { return fallback }
return value as? Date ?? fallback
}
func defaultsGetInt(forKey key: String, withFallback fallback: Int) -> Int {
guard let value = UserDefaults(suiteName: kAppGroup)?.object(forKey: key) else { return fallback }
return value as? Int ?? fallback
}
func defaultsGetString(forKey key: String, withFallback fallback: String) -> String {
guard let value = UserDefaults(suiteName: kAppGroup)?.object(forKey: key) else { return fallback }
return value as? String ?? fallback
}
func defaultsSet(_ value: Any, forKey key: String) {
UserDefaults(suiteName: kAppGroup)?.set(value, forKey: key)
UserDefaults(suiteName: kAppGroup)?.synchronize()
}
And I use them like this:
func defaultsGetSettingsEvents() -> Int {
return defaultsGetInt(forKey: kSettingsEvents, withFallback: 10)
}
func defaultsUpdateSettingsEvents(_ value: Int) {
defaultsSet(value as Int, forKey: kSettingsEvents)
}
So, when the app launches I get the events and ask for a fallback of 10 if it couldn't get that value. When I update that value, it's stored and defaults are synchronised.
In your situation where the defaults aren't accessed correctly initially, this would appear as though the defaults have been reset - because you'd be returning fallback values.
Are you sure you're accessing them in every place from your app group? Are you using Strings for the keys - perhaps there's a typo? Use constants instead: let kSettingsEvents: String = "settingsEvents"
.