Swift:如何实现排行榜?

时间:2017-09-29 23:06:52

标签: swift game-center game-center-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函数,但它不起作用。我错过了什么?

1 个答案:

答案 0 :(得分:0)

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

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

}

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