Add Leaderboard managing methods

This commit is contained in:
Simon Kellner 2020-06-10 18:32:31 +02:00
parent 1a9c075dce
commit c517a36adc

View File

@ -109,6 +109,77 @@ final class GameCenterManager: NSObject, GKMatchmakerViewControllerDelegate, GKG
} }
} }
func submitLeaderboardScore(identifier: String, score: Int64) {
let reportedScore = GKScore(leaderboardIdentifier: identifier)
reportedScore.value = score
GKScore.report([reportedScore]) { (error) in
guard error == nil else {
print(error?.localizedDescription ?? "")
return
}
}
}
func calculateLeaderboardScore(identifier: String, scoreOffset: Int64) {
GKLeaderboard.loadLeaderboards { (leaderboards: [GKLeaderboard]?, err: Error?) in
leaderboards?.forEach({ (leaderboard: GKLeaderboard) in
if leaderboard.identifier == identifier {
leaderboard.loadScores { (scores: [GKScore]?, err: Error?) in
scores?.forEach({ (score: GKScore) in
if score.player == self.localPlayer {
score.value += scoreOffset
GKScore.report([score]) { (error) in
guard error == nil else {
print(error?.localizedDescription ?? "")
return
}
}
}
})
}
}
})
}
}
//TODO: not finished -> DELETE if not usefull
// Possible way to implement matchmaking based on 2 players
// can be changed into method with fixed leaderboard and offset, boolean hasWon: true/false to calculate outcome of a match
func calculateLeaderboardScoreExperimentalMatchmaking(identifier: String, scoreOffset: Int64, opponentPlayer: GKPlayer) {
// Iterate through leaderboards
GKLeaderboard.loadLeaderboards { (leaderboards: [GKLeaderboard]?, err: Error?) in
leaderboards?.forEach({ (leaderboard: GKLeaderboard) in
if leaderboard.identifier == identifier {
leaderboard.loadScores { (scores: [GKScore]?, err: Error?) in
// Iterate through scores
var currentScore: GKScore = GKScore.init()
currentScore.value = -1
var opponetScore: GKScore = GKScore.init()
currentScore.value = 0
// Get scores of self and opponent
scores?.forEach({ (score: GKScore) in
if score.player == self.localPlayer {
currentScore = score
opponetScore = score
}
if score.player == opponentPlayer {
opponetScore = score
}
})
// do silly calculation
currentScore.value += scoreOffset + (opponetScore.value - currentScore.value)
GKScore.report([currentScore]) { (error) in
guard error == nil else {
print(error?.localizedDescription ?? "")
return
}
}
}
}
})
}
}
func match(_ match: GKMatch, didReceive data: Data, fromRemotePlayer player: GKPlayer) { func match(_ match: GKMatch, didReceive data: Data, fromRemotePlayer player: GKPlayer) {
if myMatch != match { return } if myMatch != match { return }
let jsonDecoder = JSONDecoder() let jsonDecoder = JSONDecoder()