This is such an odd issue that I have run into. I am setting and reading 2 different boolean user preferences. I update the user preferences depending on what the user is doing. I then read them when the user opens the app again. When the user kills the app, I am seeing applicationWillTerminate is always correctly called and that the 2 setters are called with the correct values. When I open the app again, the 2 values are correct (what they were last set to in applicationWillTerminate). However, about 20% of the time, they are not correct. I will do the exact scenario over and over and I will see that applicationWillTerminate is called and the 2 variables set to the correct values. However, when I open the app again, they are not the updated values about 20% of the time. I have found no pattern as to why sometimes the values are saved permanently and sometimes they aren't.
I have been researching this for awhile and can't find anyone else who has run into this intermittent issue. I tried adding synchronize() even though it's going to be deprecated and it didn't make a difference. I know for a fact my setters aren't getting called any other time.
Any ideas?
//this method is called from didFinishLaunching and only that one time
private func checkForPriorCrash() {
let appClosedProperly = UserDefaults.standard.bool(forKey: UserInterface.Keys.appClosedProperly)
let lastStateWasActive = UserDefaults.standard.bool(forKey: UserInterface.Keys.lastStateWasActive)
if !appClosedProperly && lastStateWasActive {
print("**A CRASH HAPPENED LAST TIME")
}
UserDefaults.standard.removeObject(forKey: UserInterface.Keys.appClosedProperly) //reset
UserDefaults.standard.removeObject(forKey: UserInterface.Keys.lastStateWasActive) //reset
}
private func setAppClosedProperly(_ value: Bool) {
print("set did app closed properly")
print(value)
UserDefaults.standard.set(value, forKey: UserInterface.Keys.appClosedProperly)
}
private func setLastStateWasActive(_ value: Bool) {
print("set last state was active")
print(value)
UserDefaults.standard.set(value, forKey: UserInterface.Keys.lastStateWasActive)
}
func applicationDidEnterBackground(_ application: UIApplication) {
print("in applicationDidEnterBackground")
setLastStateWasActive(false)
}
func applicationDidBecomeActive(_ application: UIApplication) {
print("in applicationDidBecomeActive")
setLastStateWasActive(true)
}
func applicationWillTerminate(_ application: UIApplication) {
print("in applicationWillTerminate")
setLastStateWasActive(false)
setAppClosedProperly(true)
}