Search code examples
iosswiftuiviewcontrollergame-centergame-center-leaderboard

Put Gamecenter in it's own class


I started coding a few weeks ago and now want to implement GameCenter in a little game I am working on.

I began by following this tutorial on YouTube and everything worked fine when I had the GC functions in my ViewController: UIViewController class. For the sake of an organised code I'd prefer to put them into their own GameCenter: GKGameCenterControllerDelegate class, which I tried to do but miserably failed.

What I did is, that I added a Swift file in Xcode in which I created a new class for the GC functions. I'm currently calling them in my ViewController with something like:

GameCenter().authenticateLocalPlayer()

Now I'm not sure how to edit this part of the code to make it work, I think it got something to do with the ViewController but I must admit that I don't understand it completely:

func showLeaderboard() {

    var vc = ViewController().view?.window?.rootViewController
    var gc = GKGameCenterViewController()
    gc.gameCenterDelegate = self
    vc?.presentViewController(gc, animated: true, completion: nil)

}

I already changed

var vc = self.view?.window?.rootViewController

to

var vc = ViewController().view?.window?.rootViewController

but am not sure what to do with

gc.gameCenterDelegate = self

I think I either need to change self to something like my ViewController(), or that I have to do something with the protocols of my classes, or both.

Can anyone help me put the GC related functions into their own class? Thank you in advance. :)


Solution

  • I made it easier for myself and just switched to Easy Game Center.