Oliver Shi
Oliver Shi

Reputation: 148

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.

Upvotes: 8

Views: 3860

Answers (2)

pawello2222
pawello2222

Reputation: 54436

iOS 14+

In iOS 14 and above we should use:

/// Class method to submit a single score to multiple leaderboards
///   score - earned by the player
///   context - developer supplied metadata associated with the player's score
///   player - the player for whom this score is being submitted
///   leaderboardIDs - one or more leaderboard IDs defined in App Store Connect
@available(iOS 14.0, *)
open class func submitScore(_ score: Int, context: Int, player: GKPlayer, leaderboardIDs: [String], completionHandler: @escaping (Error?) -> Void)

Here is an example:

GKLeaderboard.submitScore(
    score,
    context: 0,
    player: GKLocalPlayer.local,
    leaderboardIDs: ["leaderboardID"]
) { error in
    print(error)
}

Async variant

The above API is compatible with Swift 5.5 concurrency. If you want your method to be async just use:

@available(iOS 14.0, *)
open class func submitScore(_ score: Int, context: Int, player: GKPlayer, leaderboardIDs: [String]) async throws
try await GKLeaderboard.submitScore(
    score,
    context: 0,
    player: GKLocalPlayer.local,
    leaderboardIDs: ["leaderboardID"]
)

Upvotes: 6

Ron Fessler
Ron Fessler

Reputation: 2789

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)")
        }
    }))
}

Upvotes: 10

Related Questions