我一直在尝试为蓝牙连接实现 GameKit 框架,并希望使用服务器/客户端关系来减少延迟并能够区分连接的设备。我找到了这个线程,它与我正在尝试做的类似,但代码对我不起作用。这是我所拥有的:
连接方法:
-(IBAction) btnConnect:(id) sender {
if(sender == server){
[self.currentSession initWithSessionID:@"BT" displayName:nil sessionMode:GKSessionModeServer];
currentSession.available == YES;
NSLog(@"Setup Server");
}else{
[self.currentSession initWithSessionID:@"BT" displayName:nil sessionMode:GKSessionModeClient];
currentSession.available == YES;
NSLog(@"Setup Client");
}
currentSession.delegate = self;
currentSession.disconnectTimeout = 0;
[currentSession setDataReceiveHandler:self withContext:nil];
[client setHidden:YES];
[server setHidden:YES];
[disconnect setHidden:NO];
}
改变状态:
- (void)session:(GKSession *)session peer:(NSString *)peerID didChangeState:(GKPeerConnectionState)state {
NSLog(@"didChangeState was called with status: %@.", state);
switch (state)
{
case GKPeerStateConnected:
NSLog(@"connected");
break;
case GKPeerStateDisconnected:
NSLog(@"disconnected");
[self.currentSession release];
currentSession = nil;
[connect setHidden:NO];
[disconnect setHidden:YES];
break;
case GKPeerStateAvailable:
NSLog(@"Server is Available, Presenting UIALert...");
NSLog(@"%@", peerID);
peerName = [session displayNameForPeer:peerID];
NSLog(@"%@", peerName);
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Server Available!" message:[NSString stringWithFormat:@"The Server %@ is Available, Would you like to Connect?", peerName] delegate:self cancelButtonTitle:@"Decline" otherButtonTitles:@"Accept", nil];
[alert show];
[alert release];
if(selection == @"accept"){
[session connectToPeer:peerID withTimeout:15];
session.available = NO;
}else{
}
break;
}
}
didReceiveConnectionRequest:
- (void)session:(GKSession *)session didReceiveConnectionRequestFromPeer:(NSString *)peerID{
NSLog(@"Recieved Connection Request");
NSLog(@"%@", peerID);
peerName = [session displayNameForPeer:peerID];
NSLog(@"%@", peerName);
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Connection Request" message:[NSString stringWithFormat:@"The Client %@ is trying to connect.", peerName] delegate:self cancelButtonTitle:@"Decline" otherButtonTitles:@"Accept", nil];
[alert show];
[alert release];
if(selection == @"accept"){
[session acceptConnectionFromPeer:peerID error:nil];
}else{
[session denyConnectionFromPeer:peerID];
}
}
我认为我的所有设置都正确,但是没有调用 didChangeState 来通知用户另一个设备可用。我是否遗漏了什么,或者我应该尝试使用不同的方法。谢谢你的帮助