Save and Load the Number of Continues

In Chapter 15, Adding More Scenes and Saving the Game, you learned how to securely save and load game data by creating a custom GameData class. Rather than recreate the wheel, you’ll copy the resource file, GameData.swift, from the resources folder into the gloopdropproject. Note that this file is a bare-bones copy of what you made earlier.

Open Finder and drag the GameData.swift file into the Project Navigator; place it below the AdMobHelper.swift file.

Go back to Xcode, open the GameData.swift file, and below the line that reads // var propertyName: type = value, add the following:

 var​ freeContinues: ​Int​ = 1 {
 didSet​ {
 saveDataWithFileName​(​"gamedata.json"​)
  }
 }

Here, you’re making sure that any time the freeContinues property value changes, you save the data. You’re also setting the default value to 1.

Scroll down to the loadDataWithFileName(_:) method, and below the line that reads // propertyName = gd.propertyName, add the following:

 freeContinues = gd.freeContinues

If you remember, this restores the data from the file into the corresponding object—in this case, freeContinues.

To load the data, open the AppDelegate.swift file, and in the application(_:didFinishLaunchingWithOptions:) method, above the line that reads return true, add the following code:

 GameData​.shared.​loadDataWithFileName​(​"gamedata.json"​)

Finally, you need to update the numberOfFreeContinues property in the GameScene class to use the stored data. Open the GameScene.swift file and update the numberOfFreeContinues property, like so:

 var​ numberOfFreeContinues: ​Int​ {
 get​ {
 return​ ​GameData​.shared.freeContinues
  }
 set​(newValue) {
 GameData​.shared.freeContinues = newValue
 updateContinueButton​()
  }
 }

The gloopdrop project is now ready to securely read and write the number of free continues the player has earned to the device’s local storage.

You’re ready to build and run the project.

Play a few games and watch a few ads. Sometimes close the ad before earning the reward so that you can verify that players aren’t being rewarded for their impatience. Also, keep an eye on how the Continue button number changes as you earn and use continues. To test this feature thoroughly, don’t forget to exit and re-launch the game to make sure the number of continues saves and loads correctly. For best results, use the App Switcher to exit the game completely.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset