iOS,蓝牙开发!!--By帮雷

iOS的蓝牙开发大致有以下几种方式。

1 GameKit.framework

【只能存在于iOS设备之间,多用于游戏

能搜索到的demo比较多,不确切说名字了,code4app里面就有】

 

2 CoreBlueTooth.framework

【必须要支持蓝牙4.0,且iPhone4以上,即至少4s手机。可与第三方设备交互数据,

官方demo是Temperature Sensor 】

 

3 ExternalAccessory.framework

【可于第三方蓝牙设备交互,但是蓝牙设备必须经过MFI认证,需要有苹果的协议,

官方demo是 EADemo和 BTLE

 

4 Multipeer Connectivity.framework

【只能用于iOS设备之间,且iOS7才引入。主要是为了共享文件,但是文件是在sandbox内

官方demo是ios7 sample】

 

下面详细介绍一下通过蓝牙4.0的BLE开发模式在iOS下的应用方式。

首先BLE将蓝牙设备分为了两类:

一 中央设备(Central)

二 外围设备(Peripheral)

这两个设备的交互方式如下:

首先外围设备会广播自身的信息,这时中央设备如果启用检索发现功能,就会发现广播的外围设备并得到这些外围设备的列表。

中央设备选择你需要连接的外围设备连接上。这时中央设备和外围设备交互的第一步就被打通了。

详细分析接下来的步骤如下图:

 

 

左侧为中央设备(Central),右侧为外围设备(Peripheral) 。

这里以Central连接Peripheral,并向Peripheral发送数据为例,结合代码进行分析。

 

步骤如下:

1 中央设备查找外围设备

扫描周围的蓝牙扫描周围的蓝牙

NSDictionary * dic = [NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithBool:false],CBCentralManagerScanOptionAllowDuplicatesKey, nil];

[self.cbCentralMgr scanForPeripheralsWithServices:nil options:dic];

发现一个蓝牙

- (void)centralManager:(CBCentralManager *)central didDiscoverPeripheral:(CBPeripheral *)peripheral advertisementData:(NSDictionary *)advertisementData RSSI:(NSNumber *)RSSI

{

}

 

2 连接你所需要连接的Peripheral,这里就是上图中的CBPeripheral对象。

[self.cbCentralMgr connectPeripheral:peripheral options:[NSDictionary dictionaryWithObject:[NSNumber numberWithBool:YES] forKey:CBConnectPeripheralOptionNotifyOnDisconnectionKey]];

当连接上某个蓝牙之后,CBCentralManager会通知代理处理 

- (void)centralManager:(CBCentralManager *)central didConnectPeripheral:(CBPeripheral *)peripheral

{

} 

3 查找对应的服务,查找对应服务下的CBCharacteristic。

[peripheral discoverServices:nil];

返回的蓝牙服务通知通过代理实现

- (void)peripheral:(CBPeripheral *)peripheral didDiscoverServices:(NSError *)error

{

 

for (CBService* service in peripheral.services){}

[peripheral discoverCharacteristics:nil forService:service];

返回的蓝牙特征值通知通过代理实现

- (void)peripheral:(CBPeripheral *)peripheral didDiscoverCharacteristicsForService:(CBService *)service error:(NSError *)error

{

for (CBCharacteristic * characteristic in service.characteristics) {

}

}

4  向对应的CBCharactieristic发送数据。发送数据和接收数据共有4种方式。

[peripheral writeValue:data forCharacteristic:characteristic type:CBCharacteristicWriteWithResponse];

这时还会触发一个代理事件

- (void)peripheral:(CBPeripheral *)peripheral didWriteValueForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error

{

处理蓝牙发过来的数据

- (void)peripheral:(CBPeripheral *)peripheral didUpdateValueForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error

{

}

 

retrievePeripheralsWithIdentifiers 使用例子

-(IBAction) Retrieve:(id)Sender

{

[self.tvLog setText:@""];

NSMutableArray * Identifiers = [NSMutableArray array];

for (CBPeripheral * peripheral in self.peripheralArray) {

[Identifiers addObject:peripheral.identifier];

}

}

原文地址:https://www.cnblogs.com/sixindev/p/4506398.html