UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

Project 12: Challenge 2 - Score save.

Forums > 100 Days of Swift

Hello, I'm trying to understand save data in my app using UserDefault, I'm trying both ways, Codable and NSCoding and it's not working. Right now I'm try to just use UserDefaults, but still nothing happend, in my breakpoint value of score are not coming to userdefaults, anyone know why?

import UIKit

class ViewController: UIViewController {

    @IBOutlet var button1: UIButton!
    @IBOutlet var button2: UIButton!
    @IBOutlet var button3: UIButton!

    var countries = [String]()
    var score = 0
    var correctAnswer = 0
    var counter = 0
    var wrongAnswer = " "
    let userDefaults = UserDefaults.standard

    override func viewDidLoad() {
        super.viewDidLoad()

        countries += ["estonia", "france", "germany", "ireland", "italy", "monaco", "nigeria", "poland", "russia", "spain", "uk", "us"]
        button1.layer.borderWidth = 1
        button2.layer.borderWidth = 1
        button3.layer.borderWidth = 1

        button1.layer.borderColor = UIColor.lightGray.cgColor
        button2.layer.borderColor = UIColor.lightGray.cgColor
        button3.layer.borderColor = UIColor.lightGray.cgColor

        navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .add, target: self, action: #selector(showScore))

        askQuestion()

        userDefaults.setValue(score, forKey: "score")
        let savedScore = userDefaults.data(forKey: "score")
        print(savedScore)
    }
    func askQuestion(action: UIAlertAction! = nil) {

        countries.shuffle()
        correctAnswer = Int.random(in: 0...2)
        button1.setImage(UIImage(named: countries[0]), for: .normal)
        button2.setImage(UIImage(named: countries[1]), for: .normal)
        button3.setImage(UIImage(named: countries[2]), for: .normal)

        counter += 1
        title = "\(countries[correctAnswer].uppercased()), Score is: \(score)"

    }

    @IBAction func buttonTapped(_ sender: UIButton) {
        var title: String

        if sender.tag == correctAnswer {
            title = "Correct"
            score += 1
           // counter += 1
        } else {
            wrongAnswer = countries[sender.tag]
            title = "Wrong, thats a flag of \(wrongAnswer)"
            score -= 1
           // counter += 1
        }

        let ac = UIAlertController(title: title, message: "Your score is \(score)", preferredStyle: .alert)

        if counter <= 10 {
            ac.addAction(UIAlertAction(title: "Continue", style: .default, handler: askQuestion))
            present(ac, animated: true)

        }else {
        let at = UIAlertController(title: "10 guesses done", message: "You have reached the end of this game, your final Score is \(score)", preferredStyle: .alert)
                   at.addAction(UIAlertAction(title: "Restart", style: .default, handler: askQuestion))
                    present(at, animated: true)
            counter = 0
            score = 0
        }

    }

    @objc func showScore() {
        let showScore = UIAlertController(title: nil, message: "Your score is \(score)", preferredStyle: .alert)
        showScore.addAction(UIAlertAction(title: "Continue", style: .default, handler: nil))
        showScore.popoverPresentationController?.barButtonItem = navigationItem.rightBarButtonItem
        present(showScore, animated: true)
    }
}

3      

I think with this line in viewDidLoad, you might be setting the saved score in your UserDefaults to 0 everytime you launch the app:

      userDefaults.setValue(score, forKey: "score")

I think you might have better luck using PropertyObservers here. Assuming you want to save the high score, something like this might work:

  var score = 0 {
      didSet {
        let savedScore = UserDefaults.standard.integer(forKey: "score") 
        if savedScore < score {
            UserDefaults.standard.setValue(score, forKey: "score")
        }
      }
 }     

Then in viewDidLoad, you can use something like:

        let savedScore = UserDefaults.standard.integer(forKey: "score")
        print("Saved Score: \(savedScore)")

The benefit of doing this is even if there is no key "score" in your user defaults, it will just return with a value of 0

3      

Hacking with Swift is sponsored by Essential Developer

SPONSORED Join a FREE crash course for mid/senior iOS devs who want to achieve an expert level of technical and practical skills – it’s the fast track to being a complete senior developer! Hurry up because it'll be available only until April 28th.

Click to save your free spot now

Sponsor Hacking with Swift and reach the world's largest Swift community!

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.