我正在尝试使用Game Kit通过蓝牙连接两个设备。第一个设备正在运行一个应用程序,其中包含以下代码:
-(void)connect
{
GKPeerPickerController* picker;
picker = [[GKPeerPickerController alloc] init];
picker.delegate = self;
//picker.connectionTypesMask = GKPeerPickerConnectionTypeNearby;
picker.connectionTypesMask = GKPeerPickerConnectionTypeNearby;
[picker show];
}
- (void)viewDidLoad {
[super viewDidLoad];
peerStatus = kServer;
gamePacketNumber = 0;
currentSession = nil;
gamePeerId = nil;
NSString *uid = [[UIDevice currentDevice] uniqueIdentifier];
gameUniqueID = [uid hash];
[self connect];
}
- (void)peerPickerController:(GKPeerPickerController *)picker didSelectConnectionType:(GKPeerPickerConnectionType)type {
// GKSessionModeClient
// GKSessionModeServer
[self.currentSession initWithSessionID:kTankSessionID displayName:nil sessionMode:GKSessionModeClient];
currentSession.available = YES;
currentSession.delegate = self;
}
- (void)peerPickerController:(GKPeerPickerController *)picker didConnectPeer:(NSString *)peerID toSession:(GKSession *)session
{
self.gamePeerId= peerID;
//self.currentSession = session;
self.currentSession.delegate = self;
[self.currentSession setDataReceiveHandler: self withContext:nil];
// Remove the picker.
picker.delegate = nil;
[picker dismiss];
[picker autorelease];
// Start your game
}
- (void)peerPickerControllerDidCancel: (GKPeerPickerController *)picker
{
NSLog(@"peerPickerControllerDidCancel");
picker.delegate = nil;
[picker autorelease];
}
- (void)session: (GKSession*)session peer:(NSString*)peerID didChangeState:(GKPeerConnectionState)state
{
NSLog(@"finding and connecting to others sessions");
if(state == GKPeerStateAvailable){
NSLog(@"aviable and ready to conect");
[session connectToPeer:peerID withTimeout:60];
session.available =NO; //put YES si volem multiconexions sino es tancarà la sesio en conectarse 2
}
}
- (void)session:(GKSession *)session didReceiveConnectionRequestFromPeer:(NSString *)peerID{
NSLog(@"lisetn for others sessions");
NSError *error=nil;
if(amAcceptingConnetions){
if(![session acceptConnectionFromPeer:peerID error:&error]){
//Handler error
}
}else{
[session denyConnectionFromPeer:peerID];
}
}
第二个设备正在运行另一个使用与上面相同代码的应用程序,只更改了以下部分:
[self.currentSession initWithSessionID:kTankSessionID displayName:nil sessionMode:GKSessionModeServer];
两者都显示正常窗口,表示他们正在搜索其他设备,但这两个设备无法识别。这可能有什么问题?
答案 0 :(得分:0)
如果尚未分配currentSession,则需要分配它。也许尝试改变:
[self.currentSession initWithSessionID:kTankSessionID displayName:nil sessionMode:GKSessionModeClient];
对此:
self.currentSession = [[GKSession alloc] initWithSessionID:kTankSessionID displayName:nil sesssionMode:GKSessionModeClient];
您可能还想添加一个检查以查看会话是否已分配,并在创建新会话之前将其释放。如果您每次设备尝试连接时重置会话,而不是重复使用同一会话,我注意到性能和可靠性方面的一些改进。
答案 1 :(得分:0)
您还必须导入PeerPickerController以及GameKit / Gamekit.h。如果您想了解更多信息,请参阅this link。
或