检索最佳成绩 Game Center Swift

Retrieve Best Score Game Center Swift

我有麻烦了,我无法修复与从 Game Center 检索最佳分数的函数相关的错误。如果您有分数,该功能运行良好,但如果用户没有分数,它就会崩溃。

有什么建议吗?代码如下:

func retrieveBestScore() {
        if GKLocalPlayer.localPlayer().isAuthenticated {

            // Initialize the leaderboard for the current local player
            var gkLeaderboard = GKLeaderboard(players: [GKLocalPlayer.localPlayer()])
            gkLeaderboard.identifier = leaderboardID
            gkLeaderboard.timeScope = GKLeaderboardTimeScope.allTime

            // Load the scores
            gkLeaderboard.loadScores(completionHandler: { (scores, error) -> Void in

                // Get current score
                var currentScore: Int64 = 0
                if error == nil {
                    if (scores?.count)! > 0 {
                        currentScore = (scores![0] ).value
                        //We also want to show the best score of the user on the main screen
                        if self.language.contains("it"){
                            self.labelBestScore.text = "Miglior Punteggio: " + String(currentScore)
                            self.bestScore = Int(currentScore)
                        }else{
                            self.labelBestScore.text = "Your Best Score: " + String(currentScore)
                            self.bestScore = Int(currentScore)
                        }
                        print("Punteggio attuale",currentScore)
                    }
                }

            })
        }
    }

谢谢!

根据您的代码,您可能遇到了这个问题,因为强制展开了您的 'scores' 数组。

在你的闭包中尝试这样的事情:

var currentScore: Int64 = 0
if error == nil, let scores = scores {
    if scores.count > 0 {
        currentScore = scores[0].value
        //We also want to show the best score of the user on the main screen
        if self.language.contains("it"){
            self.labelBestScore.text = "Miglior Punteggio: " + String(currentScore)
            self.bestScore = Int(currentScore)
        }else{
            self.labelBestScore.text = "Your Best Score: " + String(currentScore)
            self.bestScore = Int(currentScore)
        }
        print("Punteggio attuale",currentScore)
    }
}

这是一种可以进一步压缩代码的辅助方法,我认为这也应该有效,但是如果没有看到更多代码就很难肯定地说,它可能需要一些小的改动。

guard error == nil, let scores = scores, let currentScore = scores.first?.value else {
    print("GameCenter error or no scores: \(String(describing: error)))")
    return
}

//We also want to show the best score of the user on the main screen
if self.language.contains("it"){
    self.labelBestScore.text = "Miglior Punteggio: " + String(currentScore)
    self.bestScore = Int(currentScore)
}else{
    self.labelBestScore.text = "Your Best Score: " + String(currentScore)
    self.bestScore = Int(currentScore)
}
print("Punteggio attuale",currentScore)