Prerequisites:
Setting up GameCenter Leaderboards:
Copy your LeaderboardID
that you made and lets head over to Xcode.
Working with Xcode
There are 4 functions that we will be working with.
Importing the framework and setting up the protocols
Checking if the user is signed in to GameCenter
Reporting the scores to GameCenter
Viewing leaderboards
Import GameKit import GameKit
Protocols GKGameCenterControllerDelegate
Now we want to check if the user is signed in to GameCenter
func authenticateLocalPlayer() {
let localPlayer = GKLocalPlayer.localPlayer()
localPlayer.authenticateHandler = { (viewController, error) -> Void in
if viewController != nil {
//If the user is not signed in to GameCenter, we make them sign in
let vc:UIViewController = self.view!.window!.rootViewController!
vc.presentViewController(viewController!, animated: true, completion: nil)
} else {
//Do something here if you want
}
}
}
The function below hols 2 parameters.
Identifier
which is defined as a string and used to enter your leaderboardID that you made in iTunesConnect.
score
which is defined as an Int which will be the users score to submit to iTunesConnect
func saveHighScore(identifier:String, score:Int) {
if GKLocalPlayer.localPlayer().authenticated {
let scoreReporter = GKScore(leaderboardIdentifier: identifier)
scoreReporter.value = Int64(score)
let scoreArray:[GKScore] = [scoreReporter]
GKScore.reportScores(scoreArray, withCompletionHandler: {
error -> Void in
if error != nil {
print("Error")
} else {
}
})
}
}
//This function will show GameCenter leaderboards and Achievements if you call this function.
func showGameCenter() {
let gameCenterViewController = GKGameCenterViewController()
gameCenterViewController.gameCenterDelegate = self
let vc:UIViewController = self.view!.window!.rootViewController!
vc.presentViewController(gameCenterViewController, animated: true, completion:nil)
}
//This function closes gameCenter after showing.
func gameCenterViewControllerDidFinish(gameCenterViewController: GKGameCenterViewController) {
gameCenterViewController.dismissViewControllerAnimated(true, completion: nil)
self.gameCenterAchievements.removeAll()
}