Chris Gilardi
Chris Gilardi

Reputation: 1530

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!

Upvotes: 5

Views: 705

Answers (2)

Cesare
Cesare

Reputation: 9409

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

Upvotes: 1

Rasputin
Rasputin

Reputation: 487

You can do it like CeceXX showed, or you can use Easy-Game-Center by DaRkD0G to make it easier. https://github.com/DaRkD0G/Easy-Game-Center-Swift

Upvotes: 1

Related Questions