Saving and Loading Up a Highscore in Swift Using Nsuserdefaults

Saving and Loading Up A Highscore Using Swift

Issue is with this code:

Highscore += Score

You are adding HighScore and Score then assigning back to HighScore. Change that to:

Highscore = Score

Saving highscore with NSUserDefaults

In the code you gave, you are setting "Highscore" when updating, but are attempting to get the value for "HighScore" (Notice the capital S)

This line:

if (highScoreDefault.valueForKey("HighScore") != nil){

Change it to:

if (highScoreDefault.valueForKey("Highscore") != nil){

Nsuserdefaults highscore saving

Change viewDidLoad to:

override func viewDidLoad() {
super.viewDidLoad()

if let hscore = defaults.valueForKey("highscore") {
highscore = hscore
highScoreResult.text = String(hscore)
}
}

That should load the highscore from the defaults once you're app launches.

Saving highscores with NSUserDefaults

Use NSCoding. Create a Swift file "HighScore"

import Foundation

class HighScore: NSObject {

var highScore: Int = 0

func encodeWithCoder(aCoder: NSCoder!) {
aCoder.encodeInteger(highScore, forKey: "highScore")
}

init(coder aDecoder: NSCoder!) {
highScore = aDecoder.decodeIntegerForKey("highScore")
}

override init() {
}
}

class SaveHighScore:NSObject {

var documentDirectories:NSArray = []
var documentDirectory:String = ""
var path:String = ""

func ArchiveHighScore(#highScore: HighScore) {
documentDirectories = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)
documentDirectory = documentDirectories.objectAtIndex(0) as String
path = documentDirectory.stringByAppendingPathComponent("highScore.archive")

if NSKeyedArchiver.archiveRootObject(highScore, toFile: path) {
println("Success writing to file!")
} else {
println("Unable to write to file!")
}
}

func RetrieveHighScore() -> NSObject {
var dataToRetrieve = HighScore()
documentDirectories = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)
documentDirectory = documentDirectories.objectAtIndex(0) as String
path = documentDirectory.stringByAppendingPathComponent("highScore.archive")
if let dataToRetrieve2 = NSKeyedUnarchiver.unarchiveObjectWithFile(path) as? HighScore {
dataToRetrieve = dataToRetrieve2
}
return(dataToRetrieve)
}
}

Then for your ViewController:

   import UIKit

class ViewController: UIViewController, UITextFieldDelegate {
var Score = HighScore()

override func viewDidLoad() {
super.viewDidLoad()

Score.highScore = 100
SaveHighScore().ArchiveHighScore(highScore: Score)
var retrievedHighScore = SaveHighScore().RetrieveHighScore() as HighScore
println(retrievedHighScore.highScore)

}
}

How to save a highscore to a game in swift with UserDefaults?

Try this

func saveHighScore() {
UserDefaults.standard.set(score, forKey: "HIGHSCORE")
}


Related Topics



Leave a reply



Submit