初始化GKMatchMakerViewController时出错

时间:2015-01-25 20:40:34

标签: ios swift game-center gamekit

我正在尝试制作一款使用Real-Time Matches的简单在线多人游戏。但是,当我尝试启动GKMatchmakerViewController时会抛出错误。
这是我正在运行的当前代码:

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

但是在运行时会抛出此错误:

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

现在我在尝试使用GameCenter排行榜时遇到此错误。我通过在没有rootViewController参数的情况下启动排行榜视图控制器来修复它。但是,这不是GKMatchmakerViewController的选项,它只会引发不同的错误。非常感谢任何帮助,谢谢!

编辑:我知道很多人都专注于我提供视图控制器的那一行,但是我认为错误是在我第一次初始化视图控制器的时候:var gcViewController: GKMatchmakerViewController = GKMatchmakerViewController(rootViewController: self)并且可能与某些事情有关将rootViewController设置为self。这只是一个想法。再次感谢!

1 个答案:

答案 0 :(得分:1)

好的,我已经回过头来重写代码如下:

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

所以,如果将来有人在制作GKMatchmakerViewController时遇到问题,那就是这样的。我只需要使用matchRequest而不是使用rootViewController。