-4

I have used the code below to create my GameCenter page in my app. However, I haven't been able to connect the leaderboard that I created on iTunes Connect to my code, so the app just produces a blank leaderboard page. How do I connect my Itunes Connect leaderboard to my code, and how do I make the app such that it places your score on the leaderboard, as right now the leaderboard is empty.

Here is the code I used:

override func viewDidAppear(animated: Bool) {

    //check user is logged into GameCenter
    var localPlayer = GKLocalPlayer.localPlayer()

    localPlayer.authenticateHandler = {(viewController : UIViewController!, error : NSError!) -> Void in

        if ((viewController) != nil) {

            self.presentViewController(viewController, animated: true, completion: nil)

        } else {

            println((GKLocalPlayer.localPlayer().authenticated))
        }

    }

//display leaderboard
func showLeaderboard() {

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

    gcViewController.viewState = GKGameCenterViewControllerState.Leaderboards

    gcViewController.leaderboardIdentifier = "MyLeaderboard"

    self.showViewController(gcViewController, sender: self)
    self.navigationController?.pushViewController(gcViewController, animated: true)

}

//take leaderboard away
func gameCenterViewControllerDidFinish(gcViewController: GKGameCenterViewController!) {

    self.dismissViewControllerAnimated(true, completion: nil)

}

How do I connect my Itunes Connect leaderboard to the app, and what code do I use to upload one's score to the leaderboard?

CodeSmile
  • 64,284
  • 20
  • 132
  • 217
tdh
  • 884
  • 1
  • 11
  • 22

1 Answers1

1

Firstly add the GKGameCenterControllerDelegate to your class:

class viewController: UIViewController, GKGameCenterControllerDelegate {
...
}

This is the code you need to use to authenticate the player:

func login() {
    println("Game Center Login Called")
    let localPlayer = GKLocalPlayer.localPlayer()

    // Handle the authentication
    localPlayer.authenticateHandler = {(Home: UIViewController!, error: NSError!) -> Void in
        if Home != nil {
            println("Authentication is being processed.")
            self.presentViewController(Home, animated: true, completion: nil)

        } else {
            println("Player has been successfully authenticated.")
        }
    }
}

This is the code you should use to show up the leaderboard:

func showLeaderboard() {

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

    gcViewController.viewState = GKGameCenterViewControllerState.Leaderboards

    gcViewController.leaderboardIdentifier = "YOUR_LEADERBOARD_ID"
    self.showViewController(gcViewController, sender: self)
    self.presentViewController(gcViewController, animated: true, completion: nil)
}

This code is needed when the user taps on "Done".

func gameCenterViewControllerDidFinish(gcViewController: GKGameCenterViewController!)
{
    self.dismissViewControllerAnimated(true, completion: nil)
}

You can call the authentication method login() in the viewDidLoad method:

override func viewDidLoad() {
    super.viewDidLoad() 
login()
...
}

Show up the leaderboard when the user taps on a button

@IBAction func button(sender: AnyObject) {

    showLeaderboard()
}

If you want to submit the best score:

if GKLocalPlayer.localPlayer().authenticated {
                        println("I have submitted the score to Game Center")
                        let gkScore = GKScore(leaderboardIdentifier: "Best_Score")
                        gkScore.value = Int64(bestScore)
                        GKScore.reportScores([gkScore], withCompletionHandler: ( { (error: NSError!) -> Void in
                            if (error != nil) {
                                // handle error
                                println("Error: " + error.localizedDescription);
                            } else {
                                println("Score reported: \(gkScore.value)")
                            }
                        }))
                    }
Cesare
  • 9,139
  • 16
  • 78
  • 130
  • Where in this code would I connect my iTunes Connect Leaderboard to the app? And where in this would I submit the users score to the leaderboard? – tdh Jan 25 '15 at 17:35
  • Please look accurately at my answer: `"YOUR_LEADERBOARD_ID"`. Updated the code with the score submission. – Cesare Jan 25 '15 at 18:08
  • Glad to help! :) If you think my answer has solved your issue you can mark it as correct by ticking that the white icon to turn it green. Thank you! – Cesare Jan 25 '15 at 19:15
  • For some reason, the leaderboard is coming up with the message, "No Scores". Why is that? Thank you for your fast responses. – tdh Jan 25 '15 at 19:28
  • Did you make sure to modify this line with your leaderboard ID? `let gkScore = GKScore(leaderboardIdentifier: "Best_Score")` – Cesare Jan 25 '15 at 19:30
  • I did. Could it be something to do with having no users? Except I would be counted as a user, because I have a sandbox account. – tdh Jan 25 '15 at 19:32
  • The sandbox accounts count as users. Did you use your own variable for the best score in this line of code, right? `gkScore.value = Int64(bestScore)` – Cesare Jan 25 '15 at 19:33
  • I did. I used my NSUserDefault value for highscore: `Int64(NSUserDefaults.standardUserDefaults().objectForKey("highscore") as Int!)` – tdh Jan 25 '15 at 19:35
  • Is the console printing this line of code? `println("Score reported: \(gkScore.value)")` – Cesare Jan 25 '15 at 19:35
  • Yes, it is. I didn't change any aspect of that. – tdh Jan 25 '15 at 19:37
  • Use this instead: `NSUserDefaults.standardUserDefaults().setInteger(bestScore, forKey: "highscore")}` – Cesare Jan 25 '15 at 19:37
  • To load the best score you will have to use this code: `// Load the Best Score highscore = NSUserDefaults.standardUserDefaults().integerForKey("highscore")` – Cesare Jan 25 '15 at 19:39
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/69560/discussion-between-cecexx-and-tdh). – Cesare Jan 25 '15 at 19:39
  • What would I put in place of bestScore? My highscore variable is in GameScene, so I can't use it unless I use `NSUserDefaults.standardUserDefaults().objectForKey("highscore") as Int!` – tdh Jan 25 '15 at 19:39