Retrieving Leaderboards Information Programmatically
Problem
After reporting scores to a leaderboard, you are curious as to how you can retrieve this information from the leaderboard programmatically.
Solution
Use the loadScoresWithCompletionHandler:
instance
method of the GKLeaderBoard
class, as
shown in the Discussion section.
Discussion
To retrieve a leaderboard’s scores in your app, follow these steps:
Authenticate the local player (see Authenticating the Local Player in Game Center).
Instantiate an object of type
GKLeaderBoard
.Set the category of this object to the Reference ID of the leaderboard whose data you want to read (see Creating Leaderboards in iTunes Connect).
Call the
loadScoresWithCompletionHandler:
instance method ofGKLeaderBoard
class and pass a block that returnsvoid
and accepts two parameters. The first parameter to this block is an instance ofNSArray
, which will contain the scores that were loaded from the given leaderboard. The second parameter is of typeNSError
, which will contain an error (if any).Note
Game Center might, under certain circumstances, return a valid array of scores to you and, at the same time, an error. This means that, although some of the scores were retrieved successfully, an error occurred while the scores were being fetched from Game Center. In this case, Game Center stops as soon as it receives the error and you will get some of the scores, not all of them.
Each leaderboard score in Game Center is encapsulated into an
instance of GKScore ...
Get Writing Game Center Apps in iOS now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.