Author Topic: How to display the Game Center view controller in Swift  (Read 6274 times)


  • Administrator
  • *****
  • Posts: 719
    • View Profile
How to display the Game Center view controller in Swift
« on: August 17, 2015, 03:55:20 AM »
To display the Game Center view controller in Swift:

1. Adopt the GKGameCenterDelegate protocol in the view controller that presents the Game Center view controller:

Code: [Select]
class ResultsViewController: UIViewController, GKGameCenterControllerDelegate {
2. Typically in the action method of a button in the presenting view controller, add code that launches the Game Center view controller. For example:

Code: [Select]
        // Create the Game Center view controller and configure it
        let gameCenterViewController = GKGameCenterViewController()
        gameCenterViewController.gameCenterDelegate = self
        gameCenterViewController.viewState = GKGameCenterViewControllerState.Default
        // Display the Game Center view controller
        self.presentViewController(gameCenterViewController, animated: true, completion: nil)

3. Add the gameCenterViewControllerDidFinish method to the presenting view controller, which is part of the GKGameCenterControllerDelegate protocol.

Code: [Select]
    func gameCenterViewControllerDidFinish(gameCenterViewController: GKGameCenterViewController!) {
        self.dismissViewControllerAnimated(true, completion: nil)

That's it! If the user is not logged into Game Center when this code is executed at run time, a "Game Center Unavailable - Player is not signed in" alert is displayed.

All the best!
Kevin McNeish
Author of Learn to Code in Swift:
Check out our Robot Tic-Tac-Toe app:
« Last Edit: November 15, 2015, 10:21:28 AM by kjmcneish »