swiftgame-center-leaderboard

Pulling data from a GKLeaderboard


Okay, so I have spent a large amount of time searching the internet for help on this to no success, so I would like some help.

I am making a game with SpriteKit, and I have decided to implement my own leaderboard style, rather than the clunky Game Center default. I have managed to log the user into GC, but cannot find the correct (and working) Swift 3 code for pulling information from the leaderboard. I want to pull the top 10 score, along with the current user score (if they aren't already in the top 10). The information I would like from them is position, username and score.

I know this is a fairly simple concept, but every tutorial online either uses the default GC view, or is extremely old/outdated code which no longer works. I just need to know how to pull this information from the leaderboard, then I can process it all myself!

Thank you for any help in advance!


Solution

  • It seems like Apple doesn't have proper example code in Swift, but here's a Swift version loosely based on their Objective-C example:

    let leaderboard = GKLeaderboard()
    leaderboard.playerScope = .global
    leaderboard.timeScope = .allTime
    leaderboard.identifier = "YourIdentifier"
    
    leaderboard.loadScores { scores, error in
        guard let scores = scores else { return }
        for score in scores {
            print(score.value)
        }
    }
    

    Note, this is just a translation from Apple's Objective-C code, and I haven't tested it with real data.