Saving a highscore for Game Center in Swift 2

901 views Asked by At

I recently migrated to swift 2 after downloading Xcode 7 beta and i found 2 errors that I fixed using product>clean. I am still stuck with 2 Game Centre related errors。Below is my code to save the highscore. (If it helps, this code is present on two view controllers, with a difference in leaderboard id's and score variables)

func saveHighscore(score:Int) {

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

        var scoreReporter = GKScore(leaderboardIdentifier: "ChineseWeather") //leaderboard id here

        scoreReporter.value = Int64(Score) //score variable here (same as above)

        var scoreArray: [GKScore] = [scoreReporter]

        GKScore.reportScores(scoreArray, withCompletionHandler: {(error : NSError!) -> Void in
            if error != nil {
                print("error")
            }
        })

    }

}

In the line where it starts with GKScore I receive the following error:

Cannot invoke 'reportScores' with an argument list of type '([GKScore], withCompletionHandler: (NSError!) -> Void)'

So I tried to fix this by adding scores: before scoreArray as follows:

GKScore.reportScores(scores: scoreArray, withCompletionHandler: {(error : NSError!) -> Void in

And it gives me the following error:

Missing argument for parameter 'withEligibleChallenges' in call

Help would be greatly appreciated and thank you in advance

1

There are 1 answers

2
Lucas Derraugh On BEST ANSWER

According to the prerelease documentation, the method signature has changed to be:

class func reportScores(_ scores: [GKScore],
  withCompletionHandler completionHandler: ((NSError?) -> Void)?)

This differs from the old documentation which stated:

class func reportScores(_ scores: [AnyObject]!,
  withCompletionHandler completionHandler: ((NSError!) -> Void)!)

Note the change to an optional NSError parameter as well as making the entire handler optional.

So you'll have to change your code to not have the explicit error: NSError! as your completion block parameter.