如何在 Swift 中呈现 UI 异步调用提供的数据?
How to present data provided by asynchronous call on UI in Swift?
我已经设法将以下代码收集到我的 GameCenterHelper-class。然而,我完全迷失了 Swift 的块和 completionHandlers。有人可以 post 代码示例如何在异步 completionHandler 到达时访问它提供的数据吗?
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
}
})
}
}
...
你会把它放在 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()
}
})
我已经设法将以下代码收集到我的 GameCenterHelper-class。然而,我完全迷失了 Swift 的块和 completionHandlers。有人可以 post 代码示例如何在异步 completionHandler 到达时访问它提供的数据吗?
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
}
})
}
}
...
你会把它放在 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()
}
})