I am having a problem with my UserDefault settings not persisting when my app launches. I have read other posts on this matter and most are marked solved after various tips. I have implemented all of the suggested tips (that I am aware of) and I still have this problem.
I have created the simplest sample app. The app has has a button that toggles between Login/Logout depending on the current state of a UserDefault setting called "isLoggedIn."
Here's the code...
import UIKit
class LoginViewController: UIViewController {
@IBOutlet weak var loginButton: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
}
override func viewDidAppear(_ animated: Bool) {
refreshButton()
}
@IBAction func loginButtonPressed(_ sender: UIButton) {
let isLoggedIn = UserDefaults.standard.bool(forKey: "isLoggedIn")
UserDefaults.standard.set(!isLoggedIn, forKey: "isLoggedIn")
refreshButton()
}
func refreshButton() {
let isLoggedIn = UserDefaults.standard.bool(forKey: "isLoggedIn")
loginButton.setTitle(isLoggedIn ? "Logout" : "Login", for: .normal)
}
}
When the button is clicked, the UserDefault setting is updated and the button is refreshed to display Login or Logout based on the new setting. If I run the app in the simulator I can see the button toggle which tells me that the UserDefault setting is being stored properly.
The problem occurs when I relaunch the app. The button is refreshed to show the last state of the UserDefault setting when the app was closed. But it doesn't always properly reflect the previous state. Occasionally it does but I more often it does not. I cannot see any pattern here either.
I have tried...
- Using the
set
method instead of thesetValue
method - Calling the
synchronize
method after applying the update (I'm aware that Apple says this is no longer required or suggested)
I just cannot pinpoint what I am overlooking. Does anyone have any ideas about what I am doing wrong? Please let me know if I can provide any additional code that might help.
Thanks, Joel
UPDATE
I decided to track the actual changes to the setting in the plist file itself. Upon inspection, I noticed that the setting was taking several seconds to physically update in the file. Therefore, if I wait for several seconds before closing my app then the setting will save and it will display properly when I launch again. So new question is...
- Why does it take so long for my setting to save?
- and can I ensure that the app does not close before the setting is properly saved?
It's funny because I thought that was the purpose of the synchronize
method that Apple say not to use anymore.
Thanks again!