swiftgame-centergame-center-leaderboard

Swift: How to implement a leaderboard?


On iTunes Connect I already setup everything correctly. This is what i tried:

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)

}

Finally I call the saveHighscore function but it doesn't work. What am I miss?


Solution

  • You need to authenticate the player. You can do this with this function:

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

    You need to call this function in the begin.