iOS 蓝牙4.0简单使用

导入头文件

`CoreBluetooth/CoreBluetooth.h`

遵守协议

<CBCentralManagerDelegate,CBPeripheralDelegate>

声明属性记录中心设备

@property(nonatomic,strong)CBCentralManager *mgr;

声明属性记录外围设备

@property(nonatomic,strong)CBPeripheral *peripheral;

//1. 创建中心设备
self.mgr = [[CBCentralManager alloc]init];
//2.设置代理
self.mgr.delegate = self;
//3.开始扫描外部设备
[self.mgr scanForPeripheralsWithServices:nil options:nil];

发现外围设备后调用该方法

- (void)centralManager:(CBCentralManager *)central didDiscoverPeripheral:(CBPeripheral *)peripheral advertisementData:(NSDictionary *)advertisementData RSSI:(NSNumber *)RSSI
{
// 保存扫描到的外部设备
self.peripheral = peripheral;
// 设置外围设备的代理
peripheral.delegate= self;
}

主动连接设备

[self.mgr connectPeripheral:self.peripheral options:nil];

连接外设成功

- (void)centralManager:(CBCentralManager *)central didConnectPeripheral:(CBPeripheral *)peripheral
{
//连接成功后,开始准备获取数据
//数据分两个层面,显示找指定的服务
//再找服务下的特征
// 所以先来扫描外设中的服务
// 如果传nil就是所有服务
[peripheral discoverServices:nil];

}

连接外设失败

- (void)centralManager:(CBCentralManager *)central didDisconnectPeripheral:(CBPeripheral *)peripheral error:(NSError *)error
{

}

只要扫描到服务就调用

- (void)peripheral:(CBPeripheral *)peripheral didDiscoverServices:(NSError *)error
{
//模拟获取服务中的数据
NSArray *sevices = peripheral.services;
for (CBService *sevice in sevices) {
    // 根据服务的UUID找到想要获取的服务数据
    if ([sevice.UUID.UUIDString isEqualToString:"@睡眠服务的ID"]) {
        //找到对应的服务后
        //可以继续扫描服务中的特征
        [peripheral discoverCharacteristics:nil forService:sevice];
    }
}
}

扫描到特征就调用

- (void)peripheral:(CBPeripheral *)peripheral didDiscoverCharacteristicsForService:(CBService *)service error:(NSError *)error
{
//拿到服务中的所有特征
NSArray *allChars = service.characteristics;
// 遍历每一个特征
for (CBCharacteristic *chars in allChars) {
    if ([chars.UUID.UUIDString isEqualToString:@"深度睡眠时间的id"]) {
        NSLog(@"您的睡眠时间为....");
    }
}

iOSObjective-C

483 字

2015-03-21 18:08 +0900

2015-03-21 18:08 +0900

comments powered by Disqus