如何从 iOS 的排行榜中检索分数?
How do I retrieve a score from a leaderboard in iOS?
我想在 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
returns 此错误消息:fatal error: unexpectedly found nil while unwrapping an Optional value
因为我强制展开一个包含 nil 的 Optional。
我的代码哪里出错了?
您正在声明 GKLeaderboard
,但并未对其进行初始化。另请注意,loadLeaderboardWithCompletionHandler
是 GKLeaderBoard 的 class 函数。改为这样做:
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)
}
}
}
}
}
}
作为旁注,使用隐式展开的可选值是不安全的,即任何用 !
声明的东西。以您的程序为例:您可以编译它,并且必须深入研究您的代码以找到 运行time 错误实际发生的位置。如果您声明了 var leaderBoardRequest: GKLeaderBoard?
,您将能够立即确定问题的根源,而无需编译和 运行.
我想在 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
returns 此错误消息:fatal error: unexpectedly found nil while unwrapping an Optional value
因为我强制展开一个包含 nil 的 Optional。
我的代码哪里出错了?
您正在声明 GKLeaderboard
,但并未对其进行初始化。另请注意,loadLeaderboardWithCompletionHandler
是 GKLeaderBoard 的 class 函数。改为这样做:
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)
}
}
}
}
}
}
作为旁注,使用隐式展开的可选值是不安全的,即任何用 !
声明的东西。以您的程序为例:您可以编译它,并且必须深入研究您的代码以找到 运行time 错误实际发生的位置。如果您声明了 var leaderBoardRequest: GKLeaderBoard?
,您将能够立即确定问题的根源,而无需编译和 运行.