Search code examples
swiftxcodesprite-kitgame-centergamekit

How to show a specific UIViewController when GKGameCenterViewController is dismissed?


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?


Solution

  • 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)
        }
    }