I have a framework that needs to save values locally, for that I chose UserDefaults.
However, the values are never saved, and the following read function always return ""
after restarting the app
class Preferences {
let preferences : UserDefaults
init (preferences : UserDefaults) {
self.preferences = preferences
}
// Private Key
func savePrivateKey(key : String) {
writeString(value: key, key: privateKeyKey)
}
func readPrivateKey() -> String! {
return readString(key: privateKeyKey)
}
private func readString(key : String) -> String? {
if preferences.object(forKey: key) == nil {
return "bananas"
} else {
return preferences.string(forKey: key)
}
}
private func writeString(value : String, key : String) {
preferences.set(value, forKey: key)
}
fileprivate let privateKeyKey = "privateKey"
}
Initialized with:
let preferences = Preferences(preferences: UserDefaults.standard)
I have tried:
- Simulator and physical Device
- Debug and Release
- UserDefaults and SwiftyUserDefaults
The strange thing is that this is saving the Bool
values, but not the string ones.
I thought that this might be from not using correctly UserDefaults
, but SwiftyUserDefaults
gets the same result.