Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to fetch top 10 scores from a specific gamecenter leaderboard with swift (iOS)

How to fetch top 10 scores from a specific gamecenter leaderboard in swift (iOS)?

I'd like to fetch top 10 scores and players from leaderbaord and build a custom "HALL OF FAMES" in game. How to fetch datas from leaderbaord?

like image 744
Fred The Dev Avatar asked Nov 09 '15 15:11

Fred The Dev


2 Answers

Meanwhile i found an answer:

    let leaderBoardRequest = GKLeaderboard()
    leaderBoardRequest.identifier = kGcIdHighScore // my GC Leaderboard ID
    leaderBoardRequest.playerScope = GKLeaderboardPlayerScope.Global
    leaderBoardRequest.timeScope = GKLeaderboardTimeScope.AllTime
    leaderBoardRequest.range = NSMakeRange(1,10) // top 10

    leaderBoardRequest.loadScoresWithCompletionHandler
        { (scores, error) -> Void in
            if (error != nil)
                {
                    print("Error: \(error!.localizedDescription)")
                } else if (scores != nil)
                  {

                  print("got top \(scores?.count) scores"  )

                    var ii = 0
                    while (ii < scores?.count)
                    {
                        NSLog("%i ....... %@ %i %i", Int(ii+1), scores![ii].player.alias! , scores![ii].rank , scores![ii].value )
                        ii = ii + 1
                    }

                  }
        } // end leaderBoardRequest.loadScoresWithCompletionHandler
like image 59
Fred The Dev Avatar answered Oct 02 '22 12:10

Fred The Dev


I have used the above and tweaked it to work with Swift 4 I have created a function to get scores inside it I am appending the results into an array of Tuples where: 0-element is the place achieved 1-element is the GameCenter player name 2-element is the score

I have used that to populate everything into a tableView. Tweak it to your needs

import GameKit
import UIKit 

class HighScoresViewController: UIViewController, GKGameCenterControllerDelegate, UITableViewDelegate, UITableViewDataSource {

@IBOutlet weak var scoreTableView: UITableView!

var highScores = [(String,String,String)]()
let LEADERBOARD_ID = "com.yourLeaderboard"

override func viewDidLoad() {
    super.viewDidLoad()
    scoreTableView.delegate = self
    scoreTableView.dataSource = self
    getScores()
}

func getScores(){
     let leaderBoardRequest = GKLeaderboard()
     leaderBoardRequest.identifier = LEADERBOARD_ID // my GC Leaderboard ID
     leaderBoardRequest.playerScope = GKLeaderboardPlayerScope.global
     leaderBoardRequest.timeScope = GKLeaderboardTimeScope.allTime
     leaderBoardRequest.range = NSMakeRange(1,10) // top 10

     leaderBoardRequest.loadScores
        { (scores, error) -> Void in
            if (error != nil)
            {
                print("Error: \(error!.localizedDescription)")
            } else if (scores != nil)
            {
                print("Top \(scores?.count ?? 0) scores"  )

                var ii = 0
                while (ii < scores?.count ?? 0)
                {
                    self.highScores.append(("\(scores![ii].rank)" , "\(scores![ii].player?.alias! ?? "Player")" , "\(scores![ii].value)"))
                    print(Int(ii+1) , scores![ii].rank , scores![ii].player?.alias! ?? "Player" , scores![ii].value )
                    ii = ii + 1
                }
                self.refreshTableData()                }
    } // end leaderBoardRequest.loadScoresWithCompletionHandler
}

func refreshTableData(){

    print("refreshed")
    self.scoreTableView.reloadData()
  }
func numberOfSections(in tableView: UITableView) -> Int {
    return 1
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "scoreCell", for: indexPath) as! ScoreTableViewCell
    cell.placeAchieved.text = highScores[indexPath.row].0
    cell.playerName.text = highScores[indexPath.row].1
    cell.playerScore.text = highScores[indexPath.row].2
    return cell
}

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return highScores.count
  }
}

And here is my TableViewCell file consisting of labels

import UIKit

class ScoreTableViewCell: UITableViewCell {
   @IBOutlet weak var placeAchieved: UILabel!
   @IBOutlet weak var playerName: UILabel!
   @IBOutlet weak var playerScore: UILabel!

}
like image 27
AD Progress Avatar answered Oct 02 '22 12:10

AD Progress