There are two ways to do this.
The first way uses GameKit API. You start by having two separate classes, one that implements the GKSessionDelegate
protocol and acts as a GameKit/Bluetooth "handler" and the other as the presentation UI (most likely some sort of viewcontroller with a tableview). The way you would wire it up is the handler manages the GameKit notifications etc and then calls delegate methods on the UI to update the table view when a peer connects/drops off, etc. That way, as devices come and go, your picker list should update to show who's around.
Below is some code to get you started:
- (BOOL) startPeer
{
BOOL result = NO;
if (!_session) {
_session = [[GKSession alloc] initWithSessionID:BLUETOOTHSESSION
displayName:nil
sessionMode:GKSessionModePeer];
_session.delegate = self;
[_session setDataReceiveHandler:self withContext:nil];
_session.available = YES;
result = YES;
}
return result;
}
- (void) stopPeer
{
// Set up the session for the next connection
//
[_session disconnectFromAllPeers];
_session.available = YES;
[self cleanupProgressWindow];
}
- (void) loadPeerList
{
self.peerList = [[NSMutableArray alloc] initWithArray:[_session peersWithConnectionState:GKPeerStateAvailable]];
}
- (void)session:(GKSession *)session peer:(NSString *)peerID didChangeState:(GKPeerConnectionState)state
{
BOOL peerChanged = NO;
switch(state) {
// When peer list changes, we adjust the available list
//
case GKPeerStateAvailable:
if (_peerList) {
[_peerList addObject:peerID];
peerChanged = YES;
}
break;
// When peer list changes, we adjust the available list
//
case GKPeerStateUnavailable:
if (_peerList) {
[_peerList removeObject:peerID];
peerChanged = YES;
}
break;
// Called when the peer has connected to us.
//
case GKPeerStateConnected:
// start reading and writing
break;
case GKPeerStateDisconnected:
{
if (_isWriter) {
_isConnected = NO;
_deviceToSend = nil;
[self cleanupProgressWindow];
} else {
// Other side dropped, clean up local data and reset for next connection
self.dataRead = nil;
}
}
break;
}
// Notify peer list delegate that the list has changed so they can update the UI
//
if (peerChanged)
CALLDELEGATE(_peerListDelegate, peerListChanged);
}
The second way to do it is to use standard Bonjour service selection mechanisms. GameKit is implemented on top of Bonjour (but over Bluetooth instead of WiFi) so once the two sides have gone through network reachability with each other and connected they are registered under Bonjour and act like any Bonjour service would. The GameKit way is probably a little easier, but if you already have code for WiFi it can be reused for Bluetooth as well.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…