Friday, July 17, 2015

Displaying Game Centre Leaders board from Swift

In last post, I showed how we can authenticate local player and how we can post score to default leader board.

In this post, I will show how we can display leader board using swift gamekit API. Below code shows how we can display GKGameCenterViewController. Game center viewcontroller needs delegate, which is called when view is dismissed. Also we need parent viewcontroller which will be used to display GKGameCenterViewController.
func showLeaderboard(viewController: UIViewController, 
    gameCenterDelegate: GKGameCenterControllerDelegate) {
    let gameCenterVC: GKGameCenterViewController = GKGameCenterViewController();
    gameCenterVC.leaderboardIdentifier = defaultLeaderBoard;
    gameCenterVC.gameCenterDelegate = gameCenterDelegate;
    viewController.presentViewController(gameCenterVC, animated: true, completion: nil);
}
Now we have code that can display leader board, but we need to make our class conform to GKGameCenterControllerDelegate protocol and implement required method. Below is code for delegate method. Which simply dismiss presented view controller.
func gameCenterViewControllerDidFinish(gameCenterViewController: GKGameCenterViewController!) {
    gameCenterViewController.dismissViewControllerAnimated(true, completion: nil)
}
So, as you can see it's quite simple. Hope this will be helpful.

No comments:

Post a Comment