Report Score to Leaderboard

Apple Game Frameworks and Technologies — by Tammy Coron (157 / 193)

The Pragmatic Programmers
The Pragmatic Programmers

--

👈 Show the Game Center Dashboard | TOC | Report Achievement 👉

Before you jump into the code that reports scores to leaderboards, you may want to review the GameData.swift file. In this file, you’ll see there’s a wins property. This is the property you’ll use to track the player’s number of wins. If you switch to the GameOverScene.swift file, you’ll see the didMove(to:) method increments this value by one every time the player wins a game. So, when you report the number of wins to the leaderboard, you’ll actually be passing in the value saved in this property.

All right, let’s get to it.

Switch to the GameKitHelper.swift file. First, add a new static property to hold the Leaderboard ID string, placing it at the top of the class (for easy access):

​ ​// Leaderboard IDs​
​ ​static​ ​let​ leaderBoardIDMostWins = ​"net.justwritecode.hogdice.wins"​

Be sure to use the ID you set up earlier, for example, {your bundle id}.hogdice.wins.

The next step is to create the method for reporting the score. Below the authenticateLocalPlayer() method, add the following code:

​ ​// Report Score​
​ ​func​ ​reportScore​(score: ​Int​, forLeaderboardID leaderboardID: ​String​,
​ errorHandler: ((​Error​?)->​Void​)? = ​nil​) {
​ ​guard​ ​GKLocalPlayer​.local.isAuthenticated ​else​…

--

--

The Pragmatic Programmers
The Pragmatic Programmers

We create timely, practical books and learning resources on classic and cutting-edge topics to help you practice your craft and accelerate your career.