【问题标题】:Posting score to Game Center leaderboards将分数发布到 Game Center 排行榜
【发布时间】:2014-08-28 01:24:32
【问题描述】:

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

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

我尝试使用:

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

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

【问题讨论】:

    标签: swift xcode6 game-center gamekit game-center-leaderboard


    【解决方案1】:

    首先您必须创建 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)")
            }
        }))
    }
    

    【讨论】:

    • 我实现了这个,这有点像 Jared Davidson 在 YouTube 上的教程,但我注意到我的高分没有相应地更新。 “所有时间”仍然超级未更新,你知道为什么吗?谢谢。
    • 我已经有一段时间没有用 GameKit 做了任何事情了。但是,我记得沙盒帐户和排行榜存在问题。尝试使用多个沙盒帐户进行测试。当然,请确保 leaderboardIdentifier 正确。
    • 谢谢,它现在可以正常工作了,在创建一个新的排行榜后它可以正常工作了!。
    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 2016-12-06
      • 1970-01-01
      • 1970-01-01
      • 2018-02-07
      • 1970-01-01
      • 1970-01-01
      • 2014-12-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多