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

时间:2015-12-05 07:45:49

标签: ios swift gamekit

我有两个UIViewController s,MainViewController和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内,因此我不知道要放入哪个代码

1 个答案:

答案 0 :(得分:0)

一旦您使用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.
        }
    }];
}