我需要使用 Peer Picker在新的 iPhone SDK 3.0 中寻找同行?
我并不是真的想使用它,但我确实想使用点对点蓝牙连接。是否有任何示例代码可以演示不使用 Peer Picker 的蓝牙连接?游戏GKTank Apple 提供的使用 Peer Picker,所以我不能使用它。
最佳答案
有两种方法可以做到这一点。
第一种方式使用 GameKit API。首先有两个单独的类,一个实现 GKSessionDelegate 协议(protocol)并充当 GameKit/蓝牙“处理程序”,另一个充当演示 UI(很可能是某种带有表格 View 的 View Controller )。连接它的方式是处理程序管理 GameKit 通知等,然后调用 UI 上的委托(delegate)方法,以在对等点连接/断开等时更新 TableView 。这样,当设备来来去去时,您的选择器列表应该更新以显示谁在附近。
下面是一些可以帮助您入门的代码:
- (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);
}
第二种方法是使用标准 Bonjour 服务选择机制。 GameKit 是在 Bonjour 之上实现的(但通过蓝牙而不是 WiFi),因此一旦双方实现网络可达性并连接,它们就会在 Bonjour 下注册,并像任何 Bonjour 服务一样运行。 GameKit 方式可能更简单一些,但如果您已经有 WiFi 代码,它也可以重复用于蓝牙。
关于iphone - iPhone SDK 3.0 中的 GameKit,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1049393/