Reputation: 148
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
Reputation: 54436
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)
}
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
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