Search code examples
iphonebluetoothp2pgksession

Determining when GKSession bluetooth devices go out of range


I'm using GKSession, GKSessionDelegate to implement peer to peer bluetooth connectivity between a number of iX (iPod, iPad, iPhone, ...) devices. I want to display a list of the currently available/connected devices in range.

I'm currently relying on

- (void)session:(GKSession *)session peer:(NSString *)peerID didChangeState:(GKPeerConnectionState)state

to do this. Unfortunately, this method does not appear to be reliably called when a device goes out of range. Is there a "better" way to determine if a device is in range?

Some code:

- (void)session:(GKSession *)session peer:(NSString *)peerID didChangeState:(GKPeerConnectionState)state {

    NSString* connectionStateString=
    (state==GKPeerStateAvailable)?@"available":
    (state==GKPeerStateUnavailable)?@"unavailable":
    (state==GKPeerStateConnected)?@"connected":
    (state==GKPeerStateDisconnected)?@"disconnected":@"connecting";
    // Add the peer to the Dictionary
    NSArray* details=[NSArray arrayWithObjects:[session displayNameForPeer:peerID],connectionStateString,nil];
    [connectionPeers setObject:details forKey:peerID];

    if (state == GKPeerStateAvailable) {
        NSLog(@"Adding peerID:%@",peerID);
        [session connectToPeer:peerID withTimeout:60];//'connect' to everything, so data can be sent
    }
    else if (state == GKPeerStateUnavailable || state==GKPeerStateDisconnected) {
        [connectionPeers removeObjectForKey:peerID];
    }
    [self listPlayers];
}

Solution

  • GKSession is built on Bonjour over Bluetooth and I believe that your problem is that the bonjour service is still showing as active since Bonjour doesn't invalidate service advertisements when a peer has disconnected from the network. I think the mDNS records only expire either when the mDNS cache timeout occurs ( not something you can tweak ) or when the advertising peer manually invalidates the service.

    I don't think GKSession is going to easily do what you want here via advertisement. Connected peers should however disconnect once they're out of Bluetooth range.