0

With some research, this is what I thought to be the right code. Everything seems to be working and there are NO errors. The first high score uploaded shows on the leaderboard (for both Game Center accounts I am using for testing), but any score uploaded after the initial high score (which should replace it) isn't shown (I have tried using more than one account, same issue). Here is my code (I call for this function when a Button is pressed). Everything loads up fine and the Game Center window closes perfectly with NO errors, but the score for account 1 remains at 0 (which was the first score loaded) while the score for account 2 remains at 2 (which was the first score loaded). (highScore is a saved NSInteger before this function is called) Please help!

 func saveHighscore() {

        //check if user is signed in
        if GKLocalPlayer.localPlayer().authenticated {


            let gameScoreReporter = GKScore(leaderboardIdentifier: "color_runner_leaderboard")

            gameScoreReporter.value = Int64(highScore)

            let scoreArray1: [GKScore] = [gameScoreReporter]

            GKScore.reportScores(scoreArray1, withCompletionHandler: {(NSError) -> Void in
                if NSError != nil {
                    print(NSError!.localizedDescription)
                } else {
                    print("completed Easy")
                }

            })

        }

    }

This code shows the leaderboard:

 //show leaderboard screen
func showLeader() {
    let vc = self.view?.window?.rootViewController
    let gc = GKGameCenterViewController()
    gc.gameCenterDelegate = self
    vc?.presentViewController(gc, animated: true, completion: nil)
}

This code is what uploads the score (which doesn't seem to be working after the FIRST score is loaded) and displays the leaderboard

let highScoreDefault = NSUserDefaults.standardUserDefaults()
    if highScoreDefault.valueForKey("HighScoreSaved") != nil {
        highScore = highScoreDefault.valueForKey("HighScoreSaved") as! NSInteger!
        [saveHighscore()]
    }




    [showLeader()]
Eric Aya
  • 69,473
  • 35
  • 181
  • 253
  • Possible duplicate of [iOS Game Center: Scores not showing on leaderboard in sandbox](http://stackoverflow.com/questions/8720316/ios-game-center-scores-not-showing-on-leaderboard-in-sandbox) – CStreel Dec 23 '15 at 00:34
  • Sadly that did not fix my problem. Must be code-related. – baymitchell12 Dec 23 '15 at 01:02
  • So you tried reporting from multiple accounts and it's not appearing? The other common mistake people make is they load the wrong leaderboard when checking the leaderboard. It could also be that it just hasn't loaded yet, it occasionally takes a little longer to process when using the sandbox. – CStreel Dec 23 '15 at 01:12
  • It seems to load the initial high score but it won't load it again. The first score loaded remains no matter what score should be loaded after. – baymitchell12 Dec 23 '15 at 01:19
  • So you submit Score 1 as 5 when signed into Account 1 then submit Score 2 as 10 when signed into Account 2. But when you check the High score only 5 is shown? – CStreel Dec 23 '15 at 01:25
  • Not exactly. The first score loaded for each account is shown on the leaderboard. Then nothing changes, no matter what score is uploaded on either account. – baymitchell12 Dec 23 '15 at 01:30
  • So you can't see the score from the other account on each account? – CStreel Dec 23 '15 at 01:40
  • No I can see the scores, it's just that neither of them will change. (Even when I upload a larger/smaller number) – baymitchell12 Dec 23 '15 at 01:42
  • Okay can you update your question, to include what you are observing (include the code to view the leaderboards) it seems what you are seeing has changed since you posted the question. – CStreel Dec 23 '15 at 01:44
  • Sorry for the confusion. Will update momentarily. – baymitchell12 Dec 23 '15 at 01:48
  • Question has been updated – baymitchell12 Dec 23 '15 at 02:33
  • Just checking that "color_runner_leaderboard" is your highscore board – CStreel Dec 23 '15 at 02:50
  • Yes that is correct. – baymitchell12 Dec 23 '15 at 03:32
  • Any update on this issue? – CStreel Dec 23 '15 at 22:14
  • Tryed that code exactly how it is with the exception of changing "score" to my score variable ("points"). Everything seemed to work, even printed "Posted score of \(highScore)" and it was the correct score, but the scores on the leaderboard did not change at all. (Still 0 for account 1 and 2 for account 2) – baymitchell12 Dec 23 '15 at 22:19
  • The issue was resolved but I can't explain it. I simply deleted the leaderboard and re-created it and all of a sudden it worked, with the exact code I had previously and the same amount of users. Scores updated perfectly. – baymitchell12 Dec 25 '15 at 07:24
  • Even with Paul's exact code the problem remained. I re-created the leaderboard with my original code and all of a sudden it worked perfectly. – baymitchell12 Dec 25 '15 at 07:28
  • So it's possible that you had it incorrectly configured, on the iTunes Portal. – CStreel Dec 28 '15 at 22:48

1 Answers1

0

Try this:

 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 {
              print("Posted score of \(score)")
            }
        })
      }
    }

When you want to save the high score, add this code:

self.saveHighScore("yourLeaderboardName", score: GameState.sharedInstance.highScore)

Add this class. GameState.swift:

import Foundation

class GameState {
  var score: Int
  var highScore: Int
  var coins: Int

  init() {
    // Init
    score = 0
    highScore = 0
    coins = 0

    // Load game state
    let defaults = NSUserDefaults.standardUserDefaults()

    highScore = defaults.integerForKey("highScore")
    coins = defaults.integerForKey("coins")
  }

  func saveState() {
    // Update highScore if the current score is greater
    highScore = max(score, highScore)

    // Store in user defaults
    let defaults = NSUserDefaults.standardUserDefaults()
    defaults.setInteger(highScore, forKey: "highScore")
    defaults.setInteger(coins, forKey: "coins")
    NSUserDefaults.standardUserDefaults().synchronize()
  }

  class var sharedInstance: GameState {
    struct Singleton {
        static let instance = GameState()
    }

    return Singleton.instance
  }
}

And add this helper class in it's own Swift file. Not sure if it's needed. I call it GameKitHelper.swift:

import UIKit
import Foundation
import GameKit

let PresentAuthenticationViewController = "PresentAuthenticationViewController"

class GameKitHelper: NSObject {

static let sharedInstance = GameKitHelper()


var authenticationViewController: UIViewController?
var gameCenterEnabled = false

func authenticateLocalPlayer() {

    //1
    let localPlayer = GKLocalPlayer()
    localPlayer.authenticateHandler = {(viewController, error) in

        if viewController != nil {
            //2
            self.authenticationViewController = viewController

                    NSNotificationCenter.defaultCenter().postNotificationName(PresentAuthenticationViewController, object: self)
        } else if error == nil {
            //3
            self.gameCenterEnabled = true
        }
      }

  }

  func reportAchievements(achievements: [GKAchievement], errorHandler: ((NSError?)->Void)? = nil) {
    guard gameCenterEnabled else {
        return
    }

    GKAchievement.reportAchievements(achievements, withCompletionHandler: errorHandler)
  }

    func showGKGameCenterViewController(viewController: UIViewController) {
      guard gameCenterEnabled else {
        return
    }

    //1
    let gameCenterViewController = GKGameCenterViewController()

    //2
    gameCenterViewController.gameCenterDelegate = self

    //3
    viewController.presentViewController(gameCenterViewController, animated: true, completion: nil)
 }

    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 {

                print("Posted score of \(score)")
            }
        })
      }
     }
   }

extension GameKitHelper: GKGameCenterControllerDelegate {
  func gameCenterViewControllerDidFinish(gameCenterViewController: GKGameCenterViewController) {
    gameCenterViewController.dismissViewControllerAnimated(true, completion: nil)
  }
}
Paul
  • 1,179
  • 3
  • 14
  • 38