我正在尝试使用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。
根据Apple的说法
GKSession对象提供使用蓝牙或Wi-Fi发现和连接到附近iOS设备的功能。
请帮助我尝试使用GKSession创建聊天应用。