Tutorial – Adding Game Center and leaderboards
In this tutorial we will look at adding game centre in swift. This will allow you to keep a track of player scores & make the game a challenge to keep people playing!
What you will learn
- How to setup Gamecenter in Swift
- How to authentic a user
- Check if game centre is enabled or disabled
- Setup your own leaderboards
Before proceeding with this tutorial you will need to have a developer account setup as you will need to have done following:
- Setup an explicit App identifier for your app
- Add your app to iTunes connect
- Create a development provisining profile
- Setup a test user
Once this is done go to your app in iTunes connect, and select “Game Center” from the top. It will ask you to enable it initially. Under leaderboards select Add Leaderboard and add one with the following options:
The Leaderboard Reference Name is the display name for your board, the ID is a unique identifier which we use in XCode to set and show the leaderboard scores. We will set the type as Integer, and the language to English, now setup a new single view application in XCode.
We will start off with the code side of things, I am going to assume you have setup your app identifier and added it to iTunes connect so far. Our app identifier is “seemu.iap”, make sure this is set in the Bundle identifier as per below.
Now go over to the storyboard & add some buttons and labels so it looks like the following:
Once this is done, click the assistant editor in the top left to split the view. Make sure the right side is set to ViewController.swift. For each button hold down the control key and drag it to the ViewController on the right.
For each button create an action outlet with the name as follows (Self explanatory names)
PlusOne
MinusOne
submitScore
showLeaderboard
Once this is done, also create one for the score label, however this time set the connection to Outlet and name it lblScore.
Now we have this setup, close down the assistant editor and go over to the ViewController.swift. It’s time to add our Game Center code!
First import GameKit and also add GKGameCenterControllerDelegate to the class as below. Also add the varibles score, gcEnabled, gcDefaultLeaderboard.
import UIKit import GameKit class ViewController: UIViewController, GKGameCenterControllerDelegate { var score: Int = 0 // Stores the score var gcEnabled = Bool() // Stores if the user has Game Center enabled var gcDefaultLeaderBoard = String() // Stores the default leaderboardID }
The next step is to add a function to authorise (login) the player to Game Center and get the default leaderboard.
func authenticateLocalPlayer() { let localPlayer: GKLocalPlayer = GKLocalPlayer.localPlayer() localPlayer.authenticateHandler = {(ViewController, error) -> Void in if((ViewController) != nil) { // 1 Show login if player is not logged in self.presentViewController(ViewController!, animated: true, completion: nil) } else if (localPlayer.authenticated) { // 2 Player is already euthenticated & logged in, load game center self.gcEnabled = true // Get the default leaderboard ID localPlayer.loadDefaultLeaderboardIdentifierWithCompletionHandler({ (leaderboardIdentifer: String?, error: NSError?) -> Void in if error != nil { print(error) } else { self.gcDefaultLeaderBoard = leaderboardIdentifer! } }) } else { // 3 Game center is not enabled on the users device self.gcEnabled = false print("Local player could not be authenticated, disabling game center") print(error) } } }
This code logs the player into game centre automatically, if unable to it will present the login screen. However if the user has Game centre disabled on their device it will set gcEnabled to false.
Once this is done add self.authenticateLocalPlayer() to viewDidLoad to make this code run when the app is loaded. Also add in lblScore.text = “\(score)” to viewDidLoad to set the initial score.
override func viewDidLoad() { super.viewDidLoad() lblScore.text = "\(score)" self.authenticateLocalPlayer() }
Next add the following code to add and minus the score by increment of 1.
@IBAction func PlusOne(sender: UIButton) { score++ lblScore.text = "\(score)" } @IBAction func MinusOne(sender: UIButton) { score-- lblScore.text = "\(score)" }
Next is the code for submit score button. This will submit a score the Leaderboard “LeaderboardID”. This is the name we setup earlier to submit scores to the leaderboard. We also need to submit the score as a SKScore type, so we create a new variable sScore for this. It’s value must be in the type Int64, so we cast score as a Int64 type.
@IBAction func submitScore(sender: UIButton) { let leaderboardID = "LeaderboardID" let sScore = GKScore(leaderboardIdentifier: leaderboardID) sScore.value = Int64(score) GKScore.reportScores([sScore], withCompletionHandler: { (error: NSError?) -> Void in if error != nil { print(error!.localizedDescription) } else { print("Score submitted") } }) }
Now add in the following two functions to show the leaderboard. The first one will close the leaderboard when the user clicks on the close button. The second one will show the leaderboard with the identifier “LeaderboardID” to the user.
func gameCenterViewControllerDidFinish(gameCenterViewController: GKGameCenterViewController) { gameCenterViewController.dismissViewControllerAnimated(true, completion: nil) } @IBAction func showLeaderboard(sender: UIButton) { let gcVC: GKGameCenterViewController = GKGameCenterViewController() gcVC.gameCenterDelegate = self gcVC.viewState = GKGameCenterViewControllerState.Leaderboards gcVC.leaderboardIdentifier = "LeaderboardID" self.presentViewController(gcVC, animated: true, completion: nil) }
Now that this is done you can run and test the Game centre. It may ask for you to login, put in the email address & password of one of your test users.