7

我正在苹果的 Xcode 6 beta 6 上使用 swift 创建游戏,并尝试将我的游戏的高分添加到游戏中心排行榜。我在游戏中心创建了排行榜。

那么,如何将我保存为 NSUserDefault 的高分添加到我的游戏中心排行榜?

我尝试使用:

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

但它只是崩溃。initLeaderboard 函数在 ios 8 中已被弃用,所以我不知道该怎么做。

4

2 回答 2

9

首先,您必须创建 GKScore 对象。然后设置 gkScore.value。最后,您报告分数。

// 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)")
        }
    }))
}
于 2014-10-22T15:44:08.437 回答
0

iOS 14+

在 iOS 14 及更高版本中,我们应该使用:

/// 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)

这是一个例子:

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

异步变体

上述 API 兼容 Swift 5.5 并发。如果您希望您的方法是异步的,只需使用:

@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"]
)
于 2022-01-15T20:51:30.047 回答