Search code examples
iosswiftvariableshandlercompletion

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)")

Solution

  • 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)")
        }
    }