如何从iOS中的排行榜中检索分数?

时间:2015-03-01 20:52:05

标签: ios swift game-center

我希望在Swift中显示GKPlayer的最高得分和GKLeaderboard

func login() {

if (GKLocalPlayer.localPlayer().authenticated) {

        var leaderboardRequest: GKLeaderboard!
        leaderboardRequest.identifier = "Best_Score"

        // Error: fatal error: unexpectedly found nil while unwrapping an Optional value
        func loadLeaderboardsWithCompletionHandler(completionHandler: (([AnyObject]!,
            NSError!) -> Void)!) {

             var localPlayerScore: GKScore = leaderboardRequest.localPlayerScore
        }
    }
}

尽管如此,func loadLeaderboardsWithCompletionHandler会返回此错误消息:fatal error: unexpectedly found nil while unwrapping an Optional value因为我强制解包包含nil的Optional。

我的代码错误在哪里?

1 个答案:

答案 0 :(得分:5)

您正在声明GKLeaderboard,但未初始化它。另请注意,loadLeaderboardWithCompletionHandler是GKLeaderBoard的类函数。这样做:

if (GKLocalPlayer.localPlayer().authenticated) {
    GKLeaderboard.loadLeaderboardsWithCompletionHandler { objects, error in
       if let e = error {
           println(e)
       } else {
           if let leaderboards = objects as? [GKLeaderboard] {
               for leaderboard in leaderboards {
                   if let localPlayerScore = leaderboard.localPlayerScore {
                        println(localPlayerScore)
                   }
               }
            }
       }
   }
}

作为旁注,使用隐式展开的选项是不安全的,即使用!声明的任何内容。以这里的程序为例:您可以编译它并且必须深入挖掘代码以找到实际发生运行时错误的位置。如果您已声明var leaderBoardRequest: GKLeaderBoard?,那么您可以立即识别问题的根源,而无需编译和运行。