---
title: "#57: Game Center Leaderboard Basics 🎮"
url: https://littlebitesofcocoa.com/57-game-center-leaderboard-basics
author: Jake Marsh
date: 2015-08-11
published: 2015-08-11
topics: ["Game Center"]
description: "Game Center is a great way to easily add things like leaderboards, multiplayer, challenges, etc. to your iOS or OS X game."
---

# #57: Game Center Leaderboard Basics 🎮

By Jake Marsh, August 11, 2015. HTML: https://littlebitesofcocoa.com/57-game-center-leaderboard-basics

**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.

``` swift
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:

``` swift
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!**

<img src="https://media.littlebitesofcocoa.com/bite-assets/057-game-center-leaderboard-basics-leaderboard.png" style="max-width: 185px;" />
