Topics

#57: Game Center Leaderboard Basics 🎮

Topics

Game Center is a great way to easily add things like leaderboards, multiplayer, challenges, etc. to your iOS or OS X game. Let's try it out by authenticating a user, then reporting a score to a leaderboard.

We start by grabbing the local player, and setting an authentication handler closure. This will be called automatically when it's first set. This will handle showing the login screen if necessary.

import GameKit

let leaderboardID = "com.magnus.beggarscanyon.womprats"

class GameViewController: UIViewController {
  func authenticateWithGameCenter() {
    // called inside viewDidLoad

    NSNotificationCenter.defaultCenter().addObserver(
      self, selector: Selector("authenticationDidChange:"),
      name: GKPlayerAuthenticationDidChangeNotificationName,
      object: nil
    )

      GKLocalPlayer.localPlayer().authenticateHandler = {
      viewController, error in

        guard let vc = viewController else { return }

        self.presentViewController(vc, animated: true, completion: nil)
    }
  }

    func authenticationDidChange(notification: NSNotification) {
    reportScore(1138) // report example score after user logs in
  }
}

After the user is logged in we call our reportScore function, which looks like this:

func reportScore(score: Int64) {
    let gkScore = GKScore(leaderboardIdentifier: leaderboardID)
    gkScore.value = score

    GKScore.reportScores([gkScore]) { error in
      guard error == nil  else { return }

    let vc = GKGameCenterViewController()
      vc.leaderboardIdentifier = leaderboardID
    vc.gameCenterDelegate = self
      vc.viewState = GKGameCenterViewControllerState.Leaderboards

      self.presentViewController(vc, animated: true, completion: nil)   }
}

We want to see this new score we've posted, so we finish off by creating a leaderboard view controller, and presenting it. Success!

Similar Bites