CoreBluetooth:无法发现已发现外围设备的特征

时间:2015-09-14 13:59:31

标签: ios core-bluetooth cbperipheral cbperipheralmanager

我已经编写了一些CoreBluetooth代码,我可以发现这些设备,但我似乎无法发现我发现的外设的特性。有没有人有一个很好的示例代码可以用来验证我的代码?

这就是我写的:

#import "ViewController.h"
@property(nonatomic, strong) CBCentralManager* centralmanager;
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.centralmanager = [[CBCentralManager alloc] initWithDelegate:self queue:nil];
}

- (void)centralManagerDidUpdateState:(CBCentralManager *)central
{
    CBCentralManagerState currentState =  central.state;
    NSLog(@"state %i", currentState);

    switch (central.state)
    {
        case CBCentralManagerStatePoweredOn:
        {
            NSDictionary *options = @{
                                      CBCentralManagerScanOptionAllowDuplicatesKey: @YES
                                      };
            [self.centralmanager scanForPeripheralsWithServices:nil options:options];
            NSLog(@"I just started scanning for peripherals");
            break;
        }
    }
}
- (void)centralManager:(CBCentralManager *)central
  didConnectPeripheral:(CBPeripheral *)peripheral{
    NSLog(@"connected!");
}

- (void) centralManager:(CBCentralManager *)central
  didDiscoverPeripheral:(CBPeripheral *)peripheral
      advertisementData:(NSDictionary *)advertisementData
                   RSSI:(NSNumber *)RSSI
{
    [self.centralmanager connectPeripheral:peripheral options:nil];

    if ([[advertisementData description] containsString:@“keyword”]) {


         NSLog(@"peripheral count %lu", (unsigned long)[peripheral.services count]);
         [peripheral.services count];
       for (int i=0; [peripheral.services count]; i++) {
            for (CBService *s in peripheral.services) {
                [peripheral discoverCharacteristics:nil forService:s];
            }
        }
    }
}


- (void)peripheral:(CBPeripheral *)peripheral didDiscoverCharacteristicsForService:(CBService *)service error:(NSError *)error{
    NSLog(@"did discover characteristic for service");
}

- (void)peripheral:(CBPeripheral *)peripheral didDiscoverServices:(NSArray *)serviceUuids{
    NSLog(@"discovered a peripheral's services: %@", serviceUuids);
}

1 个答案:

答案 0 :(得分:3)

看看这里: Sample Code

基本上这个过程是:

  1. 扫描设备
  2. 发现设备
  3. 连接到设备
  4. 向设备询问服务
  5. 询问服务特征
  6. 写入,读取或通过特征通知
  7. 随后您不必搜索和发现设备,因为之前发现的设备可以从缓存中检索并直接连接。

    编辑:--------------------

    阅读示例: [aPeripheral readValueForCharacteristic:aChar];

    通知示例: [aPeripheral setNotifyValue:YES forCharacteristic:aChar];

    当BLE设备返回值时,这两个调用都将导致调用- (void) peripheral:(CBPeripheral *)aPeripheral didUpdateValueForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error - 函数。使用notify时,每次设备更新其特征值时,都会自动调用此回调。