iOS 蓝牙4.0与智能硬件之间的交互
本文档主要讲述iOS苹果手机通过蓝牙4.0与智能硬件之间的交互。也就是苹果设备对智能硬件进行扫描、连接、发命令、以及接收反馈等操作:
- coreBluetooth框架
- 具体使用方法
CoreBluetooth.framework
CoreBluetooth.framework 是苹果给开发者提供的蓝牙4.0开发框架。其中包含了玉智能硬件交互的相关API。其中主要包含:
- CBCentralManager (中心设备) 也就是iPhone、iPad等设备。
- CBPeripheral (外围设备) 智能硬件设备,如:智能手环、智能电子秤、智能体温计等等市场上的智能硬件。
利用以上的两个类来完成iOS设备与智能硬件之间的操作。
初始化CBCentral
不管是什么框架初始化是最基本的,初始化如下:
#import<CoreBluetooth/CoreBluetooth.h>
@implementation BluetoothManager
-(id)init
{
self = [super init];
if(self != null)
{
self.centralManager = [[CBCentralManager alloc] initWithDelegate:nil queue:nil];
self.centralManager.delegate = self;
//扫描到的设备集合
self.foundPeripheralsArray = [NSMutableArray array];
//连接到的设备集合
self.connectPeripheralsArray = [NSMutableArray array];
...
}
return self;
}
@end
使用方法
1、检查设备是否已开启蓝牙
首先,要想与设备连接,第一件事情就是要先判断目前蓝牙开关是否开启。当然如果是关着的,并且程序内已有蓝牙权限的情况下系统也会提醒的。
- (void)centralManagerDidUpdateState:(CBCentralManager *)central
{
switch (central.state) {
case CBCentralManagerStatePoweredOn:
//蓝牙设备已开启
break;
case CBManagerStatePoweredOff:
<