Adan Sandoval
Adan Sandoval

Reputation: 466

Swift 3 How to save and load data

I'm a software development student and for a school project me and a friend are making a iOS Swift game and we are learning Swift 3 as we progress in the game aspects.

Now, we have come to the part of the development where we question how is game data going to be saved (I'm talking about scores, player's name, in-game money, if the player plays in mute or unmute.. you know that kind of stuff)

The game uses an avatar and the player can customize it, so data customization needs to be saved too. Right now we manage this data throught variables like

var eyeColor = "#04ff45"
var eyetype = 3 // And so on

I have done some research on this and found that there are various methods we could use. Like, we could use Core Data or a Dictionary or a JSON file.

I'd like to know which could be the best/easiest way to acomplish this, if we need to use any specific libraries and some basic code on how to write/read the data

Thank you very much

Upvotes: 1

Views: 2028

Answers (2)

Cyril
Cyril

Reputation: 2818

Best way to save scores is by using NSUserDefaults To save settings such as volume, you can follow the model I have below.

//When you tap on the mute button, execute this code.


   if soundSwitch { //true

       UserDefaults.standard.set(false, forKey: "SoundSwitch")
       soundSwitch = false

    } else { //false

       UserDefaults.standard.set(true, forKey: "SoundSwitch")
       soundSwitch = true

    }

If you are saving players money, name and all this other stuff, it would be better to save them in some kind of database. I'm not sure if you can do that with GameCenter.

Upvotes: 1

Mike Schmidt
Mike Schmidt

Reputation: 1065

The easiest way to save data you are working with on the device would be to use NSUserDefaults. All you have to do is create a key, and store a value under that key. You can then use the key to access the value later and it is stored on the phone's permanent memory.

For example, you would use the user defaults to create a key called "eye color", store a value under that key, and then access it later using the term that you know the value is stored under (i.e. the key). This is a very simple way of storing such information.

Upvotes: 0

Related Questions