swiftxcode6game-centergamekitgame-center-leaderboard

Posting score to Game Center leaderboards


I am creating a game using swift on apple's Xcode 6 beta 6, and trying to add the high score of my game to gamecenter leader boards. I have created the leader boards in gamecenter.

So, how do I add my high score, which I saved as a NSUserDefault, to my gamecenter leader boards?

I tried using :

GKScore.reportScore([highScore], withCompletionHandler: nil)

but it just crashes. The initLeaderboard func has been deprecated in ios 8 so I'm not sure what to do.


Solution

  • First you have to create the GKScore object. Then you set the gkScore.value. Finally, you report the score.

    // if player is logged in to GC, then report the score
    if GKLocalPlayer.localPlayer().authenticated {
        let gkScore = GKScore(leaderboardIdentifier: "leaderBoardID")
        gkScore.value = score
        GKScore.reportScores([gkScore], withCompletionHandler: ( { (error: NSError!) -> Void in
            if (error != nil) {
                // handle error
                println("Error: " + error.localizedDescription);
            } else {
                println("Score reported: \(gkScore.value)")
            }
        }))
    }