不明觉厉iOS平时生活和工作中的iOSwork

iOS蓝牙开发(CoreBluetooth)

2016-04-11  本文已影响2875人  我系哆啦

目前在iOS中蓝牙开发框架主要有以下几种

CoreBluetooth开发模式

CoreBluetooth设计类似于客户端-服务器端的设计,peripheral和central, 可以理解成外设和中心。对应他们分别有一组相关的API和类.


CoreBluetooth架构

中心的开发

  1. 建立中心角色
  2. 扫描外设(discover)
  3. 连接外设(connect)
  4. 扫描外设中的服务和特征(discover)
    • 4.1 获取外设的services
    • 4.2 获取外设的Characteristics,获取Characteristics的值,获取 Characteristics的Descriptor和Descriptor的值
  5. 与外设做数据交互(explore and interact)
  6. 订阅Characteristic的通知
  7. 断开连接(disconnect)
    </pre>

}
//根据不同的场景,会调用以下三个方法
-(void)peripheral:(CBPeripheral *)peripheral didUpdateNotificationStateForCharacteristic:(nonnull CBCharacteristic *)characteristic error:(nullable NSError *)error;
-(void)peripheral:(CBPeripheral *)peripheral didUpdateValueForCharacteristic:(nonnull CBCharacteristic *)characteristic error:(nullable NSError *)error;
-(void)peripheral:(CBPeripheral *)peripheral didWriteValueForCharacteristic:(nonnull CBCharacteristic *)characteristic error:(nullable NSError *)error;
}
</pre>

外设的开发

  1. 创建characteristics,characteristics的description 创建service,把characteristics添加到service中,再把service添加到peripheralManager中
  2. 开启广播advertising
  3. 对central的操作进行响应
    • 4.1 读characteristics请求
    • 4.2 写characteristics请求
    • 4.4 订阅和取消订阅characteristics
      </pre>

UIBackgroundModes下的蓝牙数据传输

CoreBluetooth提供了非常友好的Background支持.按一下步骤,经过测试,app进入后台后,也能收到外设特征更新的值,据WWDC2013视频介绍,就算因为内存紧张,app在后台被杀掉,系统也会自动帮我们重新启动app进行蓝牙数据传输,不过这个就没测试到,不知道有没有人做过这方便的研究.

<pre>
<key>UIBackgroundModes</key>
<array>
<string>bluetooth-central</string>
<string>bluetooth-peripheral</string>
</array>
</pre>

<pre>
_centralManager = [[CBCentralManager alloc] initWithDelegate:self
queue:nil
options:@{CBCentralManagerOptionRestoreIdentifierKey:kRestoreIdentifierKey}];
</pre>

<pre>

// NSArray *scanServices = dict[CBCentralManagerRestoredStateScanServicesKey];
// NSArray *scanOptions = dict[CBCentralManagerRestoredStateScanOptionsKey];

NSArray *peripherals = dict[CBCentralManagerRestoredStatePeripheralsKey];
for (CBPeripheral *peripheral in peripherals) {
    [self.peripherals addObject:peripheral];
    peripheral.delegate = self;
}

}
</pre>

<pre>

<pre>

Demo

不动手写代码的学框架都是耍流氓,为了更好的学习,我也是自己都敲了一遍代码,前文中的三种场景以及后台模式都实现了,可以实现中心设备和外设之前的订阅特征,读写数据等功能.希望大家都交流.下面是传送门以及界面展示😊
github传送门 CoreBluetoothDemo

主界面

![中心设备]IMG_3660.PNG](http:https://img.haomeiwen.com/i1093584/e66b42d6c1c7133f.PNG?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)

外设
上一篇 下一篇

猜你喜欢

热点阅读