如果我在我的两个ios设备中多次连接和断开蓝牙,我将获得重复的peername。
有没有办法在gkpeerpickercontroller中为蓝牙聊天应用程序获取唯一对等体的单一名称。
还附上截图。
我使用下面的代码来显示GKPeerPickerController。
-(IBAction)btnConnectClicked:(id)sender
{
[self openPeerPickerController];
}
-(IBAction)btnDisconnectClicked:(id)sender
{
[currentSession disconnectFromAllPeers];
}
-(void)openPeerPickerController
{
if (!currentSession)
{
GKPeerPickerController *peerPicker2 = [[GKPeerPickerController alloc] init];
peerPicker2.delegate = self;
peerPicker2.connectionTypesMask = GKPeerPickerConnectionTypeNearby;
[peerPicker2 show];
}
}
-(void)peerPickerController:(GKPeerPickerController *)picker didConnectPeer:(NSString *)peerID toSession:(GKSession *) session
{
NSLog(@"Peer session connected");
//set session delegate and dismiss the picker
session.delegate = self;
currentSession = session;
picker.delegate = nil;
[picker dismiss];
}
- (GKSession *)peerPickerController:(GKPeerPickerController *)picker sessionForConnectionType:(GKPeerPickerConnectionType)type
{
//create ID for session
NSString *sessionIDString = @"MTBluetoothSessionID";
//create GKSession object
GKSession *session = [[GKSession alloc] initWithSessionID:sessionIDString displayName:nil sessionMode:GKSessionModePeer];
return session;
}
-(void)peerPickerControllerDidCancel:(GKPeerPickerController *)picker
{
NSLog(@"Peer cancelled");
[currentSession disconnectFromAllPeers];
currentSession=nil;
picker.delegate = nil;
}
-(void)session:(GKSession *)session peer:(NSString *)peerID didChangeState:(GKPeerConnectionState)state
{
switch (state)
{
case GKPeerStateAvailable:
{
// not connected to session, but available for connectToPeer:withTimeout:
}
break;
case GKPeerStateUnavailable:
{
// no longer available
}
break;
case GKPeerStateConnected:
{
// connected to the session
[currentSession setDataReceiveHandler:self withContext:nil]; //set ViewController to receive data
}
break;
case GKPeerStateDisconnected:
{
// disconnected from the session
currentSession.delegate = nil;
currentSession = nil; //allow session to reconnect if it gets disconnected
}
break;
case GKPeerStateConnecting:
{
// waiting for accept, or deny response
}
break;
default:
break;
}
}
答案 0 :(得分:2)
你是GKPeerPickerControllerDelegate方法
- (GKSession *)peerPickerController:(GKPeerPickerController *)picker sessionForConnectionType:(GKPeerPickerConnectionType)type
每次都返回一个新会话。在你的情况下,它被调用两次,因此创建了两个会话。 来自文档:
当对等选择器需要会话时,它会调用此方法。您的 应用程序可以创建新会话或先前返回 创建了对等选择器的会话。
因此,您可以将会话声明为属性并编写getter,并在委托中返回会话属性,这将避免创建多个会话
@property (nonatomic, string) GKSession *session;
#define sessionIDString @"MTBluetoothSessionID"
- (GKSession) session {
if(!_session) {
//create GKSession object
_session = [[GKSession alloc] initWithSessionID:sessionIDString displayName:nil sessionMode:GKSessionModePeer];
}
return _session;
}
并将委托方法更改为:
- (GKSession *)peerPickerController:(GKPeerPickerController *)picker sessionForConnectionType:(GKPeerPickerConnectionType)type {
return self.session;
}
确保在完成后取消会话。