user2397282
user2397282

Reputation: 3818

Swift - can't get Game Center to show

I am using this code to get Game Center to appear when the user presses a button. I want this to show their high scores on the leaderboard:

@IBAction func showScores(x : UIButton) {
    var gameCenterController : GKGameCenterViewController!
    if (gameCenterController != nil) {
        gameCenterController.gameCenterDelegate = self
        self.presentViewController(gameCenterController, animated: true, completion: nil)
    }
}

But I get an error on this line:

gameCenterController.gameCenterDelegate = self

That reads,

 Type 'MenuViewController' does not conform to protocol `GKGameCenterControllerDelegate`

What am I doing wrong?

How can I implement GameCenter into my game so that users' high scores are added to the leaderboards where they can be viewed by pressing a button?

Upvotes: 3

Views: 2746

Answers (2)

Austen Chongpison
Austen Chongpison

Reputation: 3974

Make sure to declare that your presenting view controller conforms GKGameCenterControllerDelegate like so:

class MenuViewController: GKGameCenterControllerDelegate

Then In Swift, add the function below to your MenuViewController:

func gameCenterViewControllerDidFinish(gameCenterViewController: GKGameCenterViewController!)
{
    //code to dismiss your gameCenterViewController
    // for example:
    gameCenterViewController.dismissViewControllerAnimated(true, completion: nil)
}

Lastly, be sure that the gameCenterDelegate gets set on your game center view controller before you present it. For example:

var gcViewController: GKGameCenterViewController = GKGameCenterViewController()
gcViewController.gameCenterDelegate = self

Note that the delegate is gameCenterDelegate and not just delegate.

Also, here is an example on how to show your leaderboard from MenuViewController. (This code would be in MenuViewController):

func showLeaderboard()
{
    var gcViewController: GKGameCenterViewController = GKGameCenterViewController()
    gcViewController.gameCenterDelegate = self

    gcViewController.viewState = GKGameCenterViewControllerState.Leaderboards
    gcViewController.leaderboardIdentifier = "yourleaderboardid"

    self.presentViewController(gcViewController, animated: true, completion: nil)
}

Upvotes: 11

yuhua
yuhua

Reputation: 1249

It says you didn't implement the delegate method.

// Called when the player is done interacting with the view controller’s content. (required)
- (void)gameCenterViewControllerDidFinish:(GKGameCenterViewController *)gameCenterViewController

then you class may implement like this:

class YourViewController : GKGameCenterControllerDelegate
{
    func gameCenterViewControllerDidFinish(gameCenterViewController: GKGameCenterViewController!)
    {
        // do somthing
    }
}

Upvotes: 3

Related Questions