skip to Main Content

I am presenting a GKGameCenterViewController in an SKScene that inherits from the following protocol.

protocol GameCenter {}
extension GameCenter where Self: SKScene {

    func goToLeaderboard() {
        let vc = GKGameCenterViewController()
        vc.gameCenterDelegate = GameViewController()
        vc.viewState = .leaderboards
        vc.leaderboardIdentifier = "leaderboard"
        view?.window?.rootViewController?.present(vc, animated: true, completion: nil)
    }
    
}

While the GKGameCenterViewController shows up perfect, when I try to dismiss by clicking the X in the top right corner, nothing happens. I assume this is because the reference to my original GameViewController has been deallocated. How can I get this dismissal to work?

2

Answers


  1. Chosen as BEST ANSWER

    In order to present the GKGameCenterViewController on a SKScene, I needed to find the currently displayed UIViewController reference and set this as the delegate. Here is the code I used and it works:

    protocol GameCenter {}
    extension GameCenter where Self: SKScene {
        
        func goToLeaderboard() {
            var currentViewController:UIViewController=UIApplication.shared.keyWindow!.rootViewController!
            let vc = GKGameCenterViewController()
            vc.gameCenterDelegate = currentViewController as! GKGameCenterControllerDelegate
            vc.viewState = .leaderboards
            vc.leaderboardIdentifier = "leaderboard"
            currentViewController.present(vc, animated: true, completion: nil)
        }
    }
    
    

  2. According to Apple’s Documentation:

    Your delegate should dismiss the Game Center view controller. If your game paused any gameplay or other activities, it can restart those services in this method.

    This means you need to implement the gameCenterViewControllerDidFinish method in your delegate and dismiss the gameCenterViewController yourself.

    You should have something like this in your GameViewController()

    func gameCenterViewControllerDidFinish(_ gameCenterViewController: GKGameCenterViewController) {
        gameCenterViewController.dismiss(animated: true, completion: nil)
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search