Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Displaying a Game Center Leaderboard in SpriteKit

I'm working on a game, and I'm looking for help or the code to display a GameCenter leaderboard in my app when a user clicks a button. I have no clue where to start as all of the other answers seem to be for Obj-C, thanks!

EDIT: The Below answer worked perfectly, but for those wondering how to do this within SpriteKit, simply add the below methods to the GameViewController and add a Notification Center Observer

NSNotificationCenter.defaultCenter().addObserver(self, selector: "showLeaderboard", name: "showLeaderboard", object: nil)

In your SKScene Class, simply call to that observer.

NSNotificationCenter.defaultCenter().postNotificationName("showLeaderboard", object: nil)

Just to help out those wondering!

like image 638
Chris Gilardi Avatar asked Nov 01 '22 01:11

Chris Gilardi


1 Answers

Include the GKGameCenterControllerDelegate protocol within your class.

class ViewController: UIViewController, GKGameCenterControllerDelegate

This method dismisses the Game Center view when "Done" is tapped:

func gameCenterViewControllerDidFinish(gcViewController: GKGameCenterViewController!) {
    self.dismissViewControllerAnimated(true, completion: nil)
}

This function includes the code that is needed to display the leaderboard:

func showLeaderboard() {

    // declare the Game Center viewController
    var gcViewController: GKGameCenterViewController = GKGameCenterViewController()
    gcViewController.gameCenterDelegate = self

    gcViewController.viewState = GKGameCenterViewControllerState.Leaderboards

    // Remember to replace "Best Score" with your Leaderboard ID (which you have created in iTunes Connect)
    gcViewController.leaderboardIdentifier = "Best_Score"
    // Finally present the Game Center ViewController
    self.showViewController(gcViewController, sender: self)
    self.navigationController?.pushViewController(gcViewController, animated: true)
    self.presentViewController(gcViewController, animated: true, completion: nil)
}

You can now trigger the function showLeaderboard by pressing a UIButton:

@IBAction func buttonShowLeaderboard(sender: AnyObject) {
    showLeaderboard()
}
like image 58
Cesare Avatar answered Nov 16 '22 10:11

Cesare