如何从另一个 UIViewController 显示 GameCenter 的排行榜

How do I show the GameCenter's leaderboard from another UIViewController

我有两个 UIViewControllerMainViewController 和 HighScoreViewController。

MainViewController(用户在使用该应用程序时看到的初始视图控制器)中,我拥有登录 Game Center 并将高分保存到排行榜的所有方法。

override func viewDidLoad() {
    super.viewDidLoad()

    authenticateLocalPlayer()
    if totalHighScore > prevTotalHighScore {
        saveHighScore("totalHighScore", score: totalHighScore)
        prevTotalHighScore = totalHighScore
        NSUserDefaults.standardUserDefaults().setObject(prevTotalHighScore, forKey: "prevtotalhighscore")
    }
}

func authenticateLocalPlayer() {
    let localPlayer: GKLocalPlayer = GKLocalPlayer.localPlayer()

    localPlayer.authenticateHandler = {(ViewController, error) -> Void in
        if((ViewController) != nil) {
            // 1 Show login if player is not logged in
            self.presentViewController(ViewController!, animated: true, completion: nil)
        }
        else {
            print("Authentication is \(GKLocalPlayer.localPlayer().authenticated)")
        }
    }

}

func gameCenterViewControllerDidFinish(gameCenterViewController: GKGameCenterViewController) {
    gameCenterViewController.dismissViewControllerAnimated(true, completion: nil)
}

func saveHighScore(identifier: String, score: Int) {

    if GKLocalPlayer.localPlayer().authenticated {
        let scoreReport = GKScore(leaderboardIdentifier: identifier)

        scoreReport.value = Int64(score)

        let scoreArray: [GKScore] = [scoreReport]

        GKScore.reportScores(scoreArray, withCompletionHandler: { (error) -> Void in

            if error != nil {
                print(error)
            }
            else {
                print("Posted score of \(score)")
            }
        })
    }
}

首先,这是最好的实施方式吗?

其次,我的 HighScoreViewController 有一个按钮,上面写着“LEADERBOARD”,如果用户点击,我的游戏的 Game Center 排行榜就会弹出.我该如何着手实施所述按钮?我已经设置了一个按钮并且 @IBAction 方法链接到它,但我不知道要在其中放置什么代码,因为所有主要 Game Center 代码都放在 MainViewController 中.

一旦您通过 Game Center 的身份验证,哪个控制器检索排行榜就无关紧要了。你说你已经有一个方法链接到你的按钮。因此,您只需在此处添加检索代码。 Apple 的 GKLeaderBoard reference 在 obj-c 中有一个用于下载排行榜数据的示例:

GKLeaderboard *leaderboardRequest = [[GKLeaderboard alloc] init];
if (leaderboardRequest != nil)
{
    leaderboardRequest.playerScope = GKLeaderboardPlayerScopeGlobal;
    leaderboardRequest.timeScope = GKLeaderboardTimeScopeToday;
    leaderboardRequest.identifier = @" ~~ your leaderboard identifier goes here ~~ "
    leaderboardRequest.range = NSMakeRange(1,10);
    [leaderboardRequest loadScoresWithCompletionHandler: ^(NSArray *scores, NSError *error) 
    {
        if (error != nil)
        {
            // Handle the error.
        }
        if (scores != nil)
        {
            // Process the score information.
        }
    }];
}