user528432
user528432

Reputation: 421

NSuserDefaults not saving until i close the app swift

same code was working properly yesterday, not sure why not working today. I'm trying to save number of levels completed by user and unlock next. heres my code

var defaults = NSUserDefaults()
var levelsCompleted = defaults.intergerForKey("levelsCompleted")

save the user completes the level

if levelfinished() {
defaults.setInteger(nextlevel, forKey: "levelsCompleted")
defaults.synchronize()
println("level \(levelsCompleted) unlocked)
}

no matter what level i complete, it always prints users last session saved levels so if i run the first time , the value returns always 1 even when level 10th is completed but when i close the app and rerun, then 11 levels are unlocked and it returns 11 even if i complete the 20th level. So im not sure why is it not saving properly. It was working fine yesterday, as soon as i completed any level it used to print correct nextlevel value. heres the screenshot https://i.sstatic.net/1i0I6.png it always says unlocked 6

Upvotes: 2

Views: 621

Answers (2)

manecosta
manecosta

Reputation: 8772

It's hard to post code as a comment so lets try to work here.

Try changing your if statement to this:

if levelfinished() {
    defaults.setInteger(nextlevel, forKey: "levelsCompleted")
    defaults.synchronize()
    levelsCompleted = defaults.intergerForKey("levelsCompleted")
    println("level \(levelsCompleted) unlocked)
}

Upvotes: 1

Adeel Ur Rehman
Adeel Ur Rehman

Reputation: 566

Getting the completed levels like this:

var levelsCompleted = NSUserDefaults.standardUserDefaults().intergerForKey("levelsCompleted")

Save the user complete level like this:

if levelfinished() 
{
    NSUserDefaults.standardUserDefaults().setInteger(nextlevel, forKey: "levelsCompleted")
    NSUserDefaults.standardUserDefaults().synchronize()
}

Let me know if you have any questions.

Upvotes: 0

Related Questions