我正在尝试使用 GKSession 连接 2 台设备。当设备在同一个 WiFi 网络上时,它正在工作,但是当我尝试在不同的 WiFi 网络上连接设备时,它不工作。这是我的 GKSession 代码
chatSession = [[GKSession alloc] initWithSessionID:AppName displayName:name sessionMode:GKSessionModePeer];
[chatSession setDataReceiveHandler:self withContext:nil];
chatSession.delegate = self;
chatSession.available = YES;
-(void)session:(GKSession *)session peer:(NSString *)peerID didChangeState:(GKPeerConnectionState)state{
NSLog(@"state=%d", state);
if(state == GKPeerStateDisconnected)
{
// A peer disconnected
chatSession.available = YES;
NSLog(@"Disconnected");
[data removeAllObjects];
chatInput.hidden = YES;
}
else if(state == GKPeerStateConnected)
{
// You can now send messages to the connected peer(s)
NSData *imgData = UIImageJPEGRepresentation(myImage, 0.5);
if(imgData==nil)
NSLog(@"myImage is nil");
NSError *err;
//NSLog(@"pid=%@", pID);
NSLog(@"before sending image");
[chatSession sendData:imgData toPeers:[NSArray arrayWithObject:pID] withDataMode:GKSendDataReliable error:&err];
NSLog(@"after send data");
if(err)
NSLog(@"error:%@", err.description);
}
else if (state == GKPeerStateAvailable)
{
pID = peerID;
[session connectToPeer:peerID withTimeout:60*120];
}
}
-(void)session:(GKSession *)session didReceiveConnectionRequestFromPeer:(NSString *)peerID{
// We can now decide to deny or accept
bool shouldAccept = YES;
if(shouldAccept)
{
pID = peerID;
[session acceptConnectionFromPeer:peerID error:nil];
}
else
{
[session denyConnectionFromPeer:peerID];
}}
我不确定是否可以使用 GKSession。
根据苹果
GKSession 对象提供了使用蓝牙或 Wi-fi 发现并连接到附近的 iOS 设备的能力。
请帮助我尝试使用 GKSession 创建聊天应用程序。