uk_rules_ok uk_rules_ok - 6 months ago 11
iOS Question

Store Variable inside Completion handler IOS Swift

I am trying to store the local player score in pScore but after the block the variable always equals 0, How can i store the "localPlayerScore!.value" into pScore:Int.

let leaderBoardRequest = GKLeaderboard()
leaderBoardRequest.identifier = "leaderboard ID"

leaderBoardRequest.loadScoresWithCompletionHandler {
(scores, error) -> Void in
if (error != nil) {
print("Error: \(error!.localizedDescription)")
} else if (scores != nil) {
let localPlayerScore = leaderBoardRequest.localPlayerScore
self.pScore = Int(localPlayerScore!.value)
}
}

print("Local player's score: \(pScore)")

Answer

My guess is your request is asynchronous which means you can not know when it does finish. So you are trying to call the print function in the main thread which is called before the asynchronous task. Try to put break points in self.pScore = Int(localPlayerScore!.value) and print("Local player's score: \(pScore)") lines. You will understand what i mean. Anyway if you just try to print your data inside the asynchronous task you will access the result such as:

let leaderBoardRequest = GKLeaderboard()
leaderBoardRequest.identifier = "leaderboard ID"

leaderBoardRequest.loadScoresWithCompletionHandler {
    (scores, error) -> Void in
    if (error != nil) {
        print("Error: \(error!.localizedDescription)")
    } else if (scores != nil) {
        let localPlayerScore = leaderBoardRequest.localPlayerScore
        self.pScore = Int(localPlayerScore!.value)
        print("Local player's score: \(self.pScore)")
    }
}
Comments