0

I have manage to scrape up the following code to my GameCenterHelper-class. However I'm completely lost with Swift's blocks and completionHandlers. Could someone post a code example how to access the data provided by the asyncronous completionHandler on the moment it arrives?

class ShowHighscoresScene: SKScene {

override init(size: CGSize) {
  super.init(size: size)
  gameCenter.getHighscores()
  //what kind of parallel-thread-completionHandler-thingy goes here so I can show the highscores when the arrive, if the player is still using this scene?
}
...
}

class GameCenterHelper {
...
func getHighscores() {
    leaderboardReceived = nil
    let leaderboardRequest = GKLeaderboard() as GKLeaderboard!
    leaderboardRequest.identifier = "appId"
    if leaderboardRequest != nil
    {
        leaderboardRequest.loadScoresWithCompletionHandler({ (scores:[AnyObject]!, error:NSError!) -> Void in
            if (error != nil)
            {
                println("error in leaderboard highscore request")
                println(error.description)
            }
            else
            {
                self.leaderboardReceived = leaderboardRequest
            }

        })
    }
}
...
Rob
  • 415,655
  • 72
  • 787
  • 1,044
user3673836
  • 591
  • 1
  • 9
  • 23

1 Answers1

1

You would put it in the completion block of loadScoresWithCompletionHandler:

    leaderboardRequest.loadScoresWithCompletionHandler({ (scores:[AnyObject]!, error:NSError!) -> Void in
        if (error != nil)
        {
            println("error in leaderboard highscore request")
            println(error.description)
        }
        else
        {
            self.leaderboardReceived = leaderboardRequest

            // Your data-presenting code goes here:
            self.tableView.reloadData()
        }

    })
Undo
  • 25,519
  • 37
  • 106
  • 129
  • Make sure to dispatch that to the main thread. It might even be better to change `getHighScores` to take a closure, itself. – Rob Jan 18 '15 at 15:36