Search code examples
iosswiftsprite-kitgame-centernsnotifications

Integrating GameCenter in Swift with NSNotification, using SpriteKit - ViewController issue


I've tried a whole bunch of ways to get Game Center working in my SpriteKit game. Unfortunately the way I've done it in the past using ObjC and ViewControllers don't work because I'm using SKScene/ a GameScene.

This is the swift version of the code (I think):

// MARK: Game Center Integration

//login and make available
func authenticateLocalPlayer(){
    let localPlayer = GKLocalPlayer()
    print(localPlayer)
    localPlayer.authenticateHandler = {(viewController, error) -> Void in
        if ((viewController) != nil) {
            self.presentViewController(viewController!, animated: true, completion: nil)
        }else{
            print((GKLocalPlayer.localPlayer().authenticated))
        }
    }
}

//submit a score to leaderboard
func reportScoreToLeaderboard(thisScore:Int){
    if GKLocalPlayer.localPlayer().authenticated {
        let scoreReporter = GKScore(leaderboardIdentifier: "LeaderboardID")
        scoreReporter.value = Int64(thisScore)
        let scoreArray: [GKScore] = [scoreReporter]

        GKScore.reportScores(scoreArray, withCompletionHandler: { (error: NSError?) -> Void in
            if error != nil {
                print(error!.localizedDescription)
            } else {
                print("Score submitted")
            }
        })
    }
}

//show leaderboard (call from button or touch)
func showLeaderboard() {
    let vc = self.view?.window?.rootViewController
    let gc = GKGameCenterViewController()
    gc.gameCenterDelegate = self
    vc?.presentViewController(gc, animated: true, completion: nil)
} 

//hides view when finished
func gameCenterViewControllerDidFinish(gameCenterViewController: GKGameCenterViewController){
    gameCenterViewController.dismissViewControllerAnimated(true, completion: nil)
}

Unfortunetely, no matter what I try, I either get this error:

Attempting to load the view of a view controller while it is deallocating is not allowed and may result in undefined behavior

... or it just crashes.

I've read that NSNotifications can be used? But how?

I'm guessing the best way is to set it all up in the GameViewController.swift and use NSNotifications to communicate with the RootViewController from the GameScene? I can't seem to find a tutorial or example though.


Solution

  • Use delegation when a view controller needs to change views, do not have the view itself change views, this could cause the view trying to deallocating while the new view is being presented, thus the error you are getting