我很麻烦,我无法修复与功能有关的错误,无法从游戏中心获取最佳分数。如果您有一个分数,该功能运行良好,但是如果用户没有分数,该功能将崩溃。
有什么建议吗?下面的代码:
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)
}
}
})
}
}
谢谢!
答案 0 :(得分:1)
根据您的代码,由于强制展开“分数”数组,您可能遇到了此问题。
在关闭时尝试这样的事情:
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)