如何使用游戏技术Sprite Kit(设置为快速编程语言)将Game Center排行榜和成就添加到Xcode 6的iOS应用程序中?

最佳答案

这是我的游戏中心代码。您将其放入游戏场景代码中。
您必须在iTunes连接中创建一个排行榜,并且LeaderboardName必须与您在代码中放置的排行榜匹配。 (我称其为“leaderboardName”)。将这个委托添加到类GKGameCenterControllerDelegate的顶部也很重要

//MARK: GameCenter

//send high score to leaderboard
func saveHighscore(score:Int) {

    //check if user is signed in
    if GKLocalPlayer.localPlayer().authenticated {

        var scoreReporter = GKScore(leaderboardIdentifier: "leaderboardName") //leaderboard id here

        scoreReporter.value = Int64(score) //score variable here (same as above)

        var scoreArray: [GKScore] = [scoreReporter]

        GKScore.reportScores(scoreArray, {(error : NSError!) -> Void in
            if error != nil {
                println("error")
            }
        })

    }

}


//shows leaderboard screen
func showLeader() {
    var vc = self.view?.window?.rootViewController
    var gc = GKGameCenterViewController()
    gc.gameCenterDelegate = self
    vc?.presentViewController(gc, animated: true, completion: nil)
}

//hides leaderboard screen
func gameCenterViewControllerDidFinish(gameCenterViewController: GKGameCenterViewController!)
{
    gameCenterViewController.dismissViewControllerAnimated(true, completion: nil)

}

//initiate gamecenter
func authenticateLocalPlayer(){

    var localPlayer = GKLocalPlayer.localPlayer()

    localPlayer.authenticateHandler = {(viewController, error) -> Void in

        if (viewController != nil) {
            let vc: UIViewController = self.view!.window!.rootViewController!
            vc.presentViewController(viewController, animated: true, completion: nil)
        }

        else {
            println((GKLocalPlayer.localPlayer().authenticated))
        }
    }

}

09-26 19:57