-4

I'm learning application development working on a quiz game. I'd like to add statistics to the game. For example, the average score since the app has been downloaded. How can I store the scores on the device in order to reuse them after the app has been closed?

rmaddy
  • 314,917
  • 42
  • 532
  • 579
  • Possible duplicate of [iOS: How to store username/password within an app?](https://stackoverflow.com/questions/6972092/ios-how-to-store-username-password-within-an-app) – Sphinx Apr 04 '18 at 00:32

2 Answers2

0

You should take a look at UserDefault. It's basically a dictionary that persists until the user uninstalls your app. I like to write a wrapper around it to get strong typing and ease of reference:

struct Preferences {
    static func registerDefaults() {
        UserDefaults.standard.register(defaults: [kAverageScore: 0])
    }

    // Define your key as a constant so you don't have to repeat a string literal everywhere
    private static let kAverageScore = "averageScore"
    static var averageScore: Double {
        get { return UserDefaults.standard.double(forKey: kAverageScore) }
        set { UserDefaults.standard.set(newValue, forKey: kAverageScore) }
    }
}

Here's how to use it: before you call it for the first time in your app, you must register the defaults. These are the values that your app ships with. On iOS, it only really matters for the very first time the user launches your app. On OS X, do this every time your app starts because the user can delete the app's preferences from ~/Library/Application Support.

// You usually do this in viewDidLoad
Preferences.registerDefaults()

From then on, getting and setting the property is easy:

let averageScore = Preferences.averageScore
Preferences.averageScore = 5.5
Code Different
  • 90,614
  • 16
  • 144
  • 163
  • Do not use `setValue(_:forKey:)` to store data in UserDefaults unless you have a clearly understood need to use key-value coding. Use the proper `set(_:forKey:)` method provided by UserDefaults. – rmaddy Apr 04 '18 at 01:33
  • Thanks, I did it ! But I didn't use the `registerDefaults` method in `viewDidLoad` because it would have reset the `averageScore` each time, especially what I didn't want. – Paul Delano Apr 04 '18 at 06:48
  • You misunderstood the purpose of `registerDefaults`: it's there to provide a seed value to the property when your app launches for the very first time. It will not overwrite the property if the property already exists in your `UserDefaults` – Code Different Apr 04 '18 at 12:00
-2

You should take a look at UserDefaults Example

let defaults = UserDefaults.standard
defaults.set(25, forKey: "Age")
defaults.set(true, forKey: "UseTouchID")
defaults.set(Double.pi, forKey: "Pi")

To read values back

let age = defaults.integer(forKey: "Age")
let useTouchID = defaults.bool(forKey: "UseTouchID")
let pi = defaults.double(forKey: "Pi")

UserDefaults

Graciano
  • 508
  • 4
  • 11