简体   繁体   中英

Error initializing GKMatchMakerViewController

I am trying to make a simple online multiplayer game which uses Real-Time Matches. However, when I try to initiate the GKMatchmakerViewController it throws an error.
Here is the current code I am running:

func openMatchmaker() {
    var gcViewController: GKMatchmakerViewController = GKMatchmakerViewController(rootViewController: self)

    gcViewController.matchmakerDelegate = self

    gcViewController.hosted = false
    gcViewController.matchRequest.minPlayers = 2
    gcViewController.matchRequest.maxPlayers = 2
    gcViewController.matchRequest.defaultNumberOfPlayers = 2

    self.showViewController(gcViewController, sender: self)
    self.navigationController?.pushViewController(gcViewController, animated: true)
}

However it throws this error when run:

Terminating app due to uncaught exception 'UIViewControllerHierarchyInconsistency', reason: 'adding a root view controller <GameName.GameViewController: 0x12e61a930> as a child of view controller:<GKMatchmakerViewController: 0x12e92b800>'

Now I have had this error previously when attempting to use GameCenter leaderboards. I fixed it by initiating the leaderboard view controller without the rootViewController parameter. However, that is not an option for GKMatchmakerViewController and it will simply throw a different error. Any help is greatly appreciated thanks!

EDIT: I know a lot of you have focused on the line where I present the view controller, however I think the error but be when I first initialize the view controller: var gcViewController: GKMatchmakerViewController = GKMatchmakerViewController(rootViewController: self) and might have something to do with setting the rootViewController to self. That's just a thought though. Thanks again!

Okay, I have gone back and rewritten the code as follows:

func displayGameMaker(){
    if (GKLocalPlayer.localPlayer().authenticated){
        var request = GKMatchRequest()
        request.minPlayers = 2
        request.maxPlayers = 2
        request.inviteMessage = "You have been invited to a game!"
        var vc = GKMatchmakerViewController(matchRequest: request)
        vc.matchmakerDelegate = self
        self.showViewController(vc, sender: self)
    }
}

So, if anyone in the future has trouble making a GKMatchmakerViewController this is how. I just needed to use a matchRequest rather than using the rootViewController.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM