Swift: 如何实现排行榜?

Swift: How to implement a leaderboard?

在 iTunes Connect 上,我已经正确设置了所有内容。这是我试过的:

func saveHighscore(number: Int){

    if GKLocalPlayer.localPlayer().isAuthenticated {

        let scoreReporter = GKScore(leaderboardIdentifier: "This")
        scoreReporter.value = Int64(number)
        let scoreArray : [GKScore] = [scoreReporter]

        GKScore.report(scoreArray, withCompletionHandler: nil)

    }

}

func showLeaderBoard(){
    let viewController = self.view.window?.rootViewController
    let gcvc = GKGameCenterViewController()

    gcvc.gameCenterDelegate = self

    viewController?.present(gcvc, animated: true, completion: nil)


}

func gameCenterViewControllerDidFinish(_ gameCenterViewController: GKGameCenterViewController) {
    gameCenterViewController.dismiss(animated: true, completion: nil)

}

最后我调用了 saveHighscore 函数,但它不起作用。我想念什么?

您需要对播放器进行身份验证。您可以使用此功能执行此操作:

func authPlayer (){
    let localPlayer = GKLocalPlayer.localPlayer()
    localPlayer.authenticateHandler = {
    (view, error) in
        if view != nil{
            self.present(view!, animated: true, completion: nil)
        }
        else {
            print(GKLocalPlayer.localPlayer().isAuthenticated)
        }
    }

}

您需要在开始时调用此函数。