Search code examples
swiftuserdefaults

UserDefaults is NOT keeping data saved after app is closed and re-opened


A problem that I am currently encountering is that the recordData value does not remain saved if I leave the app and come back. It does remain saved if I play the game again without closing the app.

If I close and reopen the app, ant new score will replace the recordData, and thus, update the highScoreLabel1.text with the new score. This will occur even if the new score is a lesser value than the previously saved recordData value. Please note that the highScoreLabel1.text does show the proper High Score when the app is re-opened. It just doesn't keep it after any new score is made. So, basically its seems like UserDefaults is only working while the app is open and is not persisting after the app is closed and re-opened. I probably need something in AppDelegate. Any suggestions?

Here's my highScore and UserDefaults code:

var recordData = 0

override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)

    highScoreLabel1A.text = String(UserDefaults.standard.integer(forKey: "Record1A"))
}

func highScore() {
    guard gameMode == 0, let score = Int(scoreLabel.text!), score > recordData else { return }
    recordData = score
    UserDefaults.standard.set(recordData, forKey: "Record1A")
    highScoreLabel1B.text = String(recordData)
}

Solution

  • Simply add a line in viewWillAppear that will set recordData to the previously saved High Score ...

    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
    
        // high score code
        highScoreLabel1A.text = String(UserDefaults.standard.integer(forKey: "Record1A"))
    
        // This code will set recordData to the previously saved High Score value, thus avoiding "0"
        recordData = UserDefaults.standard.integer(forKey: "Record1A")
    
    }