我想知道如何在游戏会话进行时获取本地玩家的断开连接消息,而我们无法将数据传达给其他玩家。由于文档中没有任何内容表明“当您的连接失败时,此方法会通知您”,我有点不知所措。
我试图使用这段代码,希望它可以工作,但这是徒劳的。 “我们已断开连接。”消息永远不会被触发。
- (void)match:(GKMatch *)theMatch player:(NSString *)playerID didChangeState:(GKPlayerConnectionState)state {
if (self.match != theMatch) return;
switch (state) {
case GKPlayerStateDisconnected:
//disconnected
NSLog(@"player status changed: disconnected");
matchStarted = NO;
GKLocalPlayer *player = [GKLocalPlayer localPlayer];
if ([playerID isEqualToString:player.playerID]) {
// We have been disconnected
NSLog(@"We're disconnected.");
}
if ([delegate respondsToSelector:@selector(matchEnded)]) {
[delegate matchEnded];
}
break;
}
}
我发现的唯一其他行可能告诉我们,当我们实际发送这样的数据时,我们无法进行通信:
- (void)sendRandomMatchData:(NSData *)data {
GKMatch *match = [GCHelper sharedInstance].match;
BOOL success = [match sendDataToAllPlayers:data
withDataMode:GKMatchSendDataReliable
error:nil];
if (!success) {
[self matchEnded];
}
}
但我认为如果对手断线并且我们无法向他们发送消息,那么“成功”也将是假的。
我有一个非常严格的游戏逻辑,如果有人断线我需要通知他们他们无法继续比赛并且他们已经输了。
非常感谢任何帮助。
答案 0 :(得分:1)
有两个地方可以做到这一点,两者都在GKMatchDelegate协议中。
第一个是实施:
- (void)match:(GKMatch *)match player:(NSString *)playerID
didChangeState:(GKPlayerConnectionState)state
{
}
如果是2人匹配 ,那么您可以抓住断开连接的第二个位置是:
- (BOOL)match:(GKMatch *)theMatch shouldReinvitePlayer:(NSString *)playerID
{
}
GKMatch
终止时,这些事件都会可靠地触发。如果斯坦的答案回答了你的问题,那么我高度建议在任何可用的地方抓住NSError
。可以节省很多时间。
所以发送数据并捕获错误:
NSError* nsErr ;
int result = [theMatch sendData:nsd toPlayers:theMatch.playerIDs
withDataMode:GKMatchSendDataReliable error:&nsErr] ;
if( !result ) { // NO if the match was unable to queue the data.
error( nsErr, "Failed to sendRoundtripPing" ) ;
}
答案 1 :(得分:0)
如何在以下代码行之后检查error
:
BOOL success = [match sendDataToAllPlayers:data
withDataMode:GKMatchSendDataReliable
error:nil]; //replace nil with NSError variable
也许error
会为您提供额外的信息
另一个想法是创建NSTimer并设置一些时间来进行移动/转弯。如果某个玩家在一段时间内没有成功,那么假设此玩家已断开连接。你也可以检查你的互联网连接状态,以确定你有连接,因为你可能丢失了它,这就是你无法发送/接收任何数据的原因。
此外,您可以定期检查每个玩家,使用GC向他们发送一些简短的数据,以便他们回答您。这样你就可以确保所有玩家都“活着”或者发现一些“僵尸”
请记住,如果玩家使用“主页”按钮将游戏移动到后台,您将无法检测到游戏中的cuz代码无法执行。而这种情况并不意味着玩家是“僵尸”。玩家可能会通过电话或其他应用程序等其他应用程序忙碌。播放器可以临时松散Internet连接。这意味着他/她可以很快回归游戏......