I have two UIViewController
s, MainViewController
and HighScoreViewController.
In the MainViewController
(the initial view controller that the user sees upon using the app) I have all the methods to log into Game Center
and save the high score to a leaderboard.
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)")
}
})
}
}
First of all, is this the best way to implement as such?
Secondly, my HighScoreViewController
has a button that says 'LEADERBOARD' where if the user taps on, Game Center
leaderboard for my game would pop up. How do I go about implementing said button? I already have a button set up and and @IBAction
method linked to it, but I have no idea what code to place in it since all of the main Game Center
code is placed inside the MainViewController
.
Once you're authenticated with Game Center, it doesn't matter which controller retrieves the leaderboard. You say you already have a method linked to your button. So, you'll just add the retrieval code there. Apple's GKLeaderBoard reference has an example in obj-c for downloading leaderboard data:
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.
}
}];
}