实现蓝牙通信主要依靠一下2个类:GKPeerPickerController用于检测设备建立连接,GKSession 主要用于通信。
@property (strong, nonatomic) GKPeerPickerController * peerPickerController;
@property (strong, nonatomic) GKSession * session;
首先,ios的蓝牙功能并不想android的蓝牙功能那样直接可以传送文件和图片,音乐。ios蓝牙集成与gameKit框架,个人理解主要是用于在线游戏的即使交流和文件的传送。
GKPeerPickerController,GKSession只向开发者提供接口并不像android一样直接向用户开放,所以我们会发现两台iphone(没有越狱的)之间在设置里面开启蓝牙并不能发现对方。若要实现像android一样传送文件,必须依靠专用的app来实现,其中app的核心就是上述两个类。
接下来需要两台iphone,每台设备都安装demon程序。
点击连接按钮,显示自带的搜索画面
-(IBAction)connect:(id)sender
{
_peerPickerController = [[GKPeerPickerController alloc]init];
_peerPickerController.delegate = self;
_peerPickerController.connectionTypesMask = GKPeerPickerConnectionTypeNearby;
[_peerPickerController show];
}
如中断搜索,cancel触发下面的delegate
-(void)peerPickerControllerDidCancel:(GKPeerPickerController *)picker
{
NSLog(@"connect cancel");
}
在搜索的列表中选中一台设备则触发下面的delegate 保存这次通信的会话session
-(void)peerPickerController:(GKPeerPickerController *)picker didConnectPeer:(NSString *)peerID toSession:(GKSession *)session
{
NSLog(@"connected to %@",peerID);
self.session = session;
self.session.delegate = self;
[self.session setDataReceiveHandler:self withContext:nil];
self.peerPickerController.delegate = nil;
[self.peerPickerController dismiss];
}
[self.session setDataReceiveHandler:self withContext:nil];设置self为当前通信的数据接受者,查看文档可以发现调用该函数的时候。已经绑定类一个SEL,
收到消息就会自动调用 receiveData:fromPeer:inSession:context:
/* Set the handler to receive data sent from remote peers.
*/
- (void)setDataReceiveHandler:(id)handler withContext:(void *)context; // SEL = -receiveData:fromPeer:inSession:context:
/*
*接受发送过来的数据
*/
-(void)receiveManyData:(NSData *)data fromPeer:(NSString *)peer inSession:(GKSession *)session context:(void *)context {
NSString* str;
str = [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding];
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Data received"
message:str
delegate:self
cancelButtonTitle:@"OK"
otherButtonTitles:nil];
[alert show];
// UIImage * image =[UIImage imageWithData:data];
// self.sendImage.image = image;
}
建立连接后发送数据 文本消息默认只支持英文,(怎么实现发送中文呢?)
-(IBAction)send:(id)sender
{
NSString * str = [NSString stringWithString:self.content.text];
NSData * sendData = [str dataUsingEncoding:NSASCIIStringEncoding];
[self.session sendDataToAllPeers:sendData withDataMode:GKSendDataReliable error:nil];
}
//通信过程中连接状态发生变化触发当前delegate
-(void)session:(GKSession *)session peer:(NSString *)peerID didChangeState:(GKPeerConnectionState)state
{
switch (state){
case GKPeerStateConnected:
NSLog(@"session connected");
break;
case GKPeerStateDisconnected:
NSLog(@"session disconnected");
break;
default:
break;
}
}
以上是实现蓝牙通讯的几个主要过程