CoreBluetooth - 没有发现服务

时间:2015-03-21 09:13:43

标签: ios objective-c iphone core-bluetooth

我遇到了CoreBluetooth的一个有趣问题。我正在使用iPhone 6 Plus和iPhone 4S进行测试。两种设备都在8.2

我在班级的init方法中有以下设置:

 _centralManager = [[CBCentralManager alloc] initWithDelegate:self  
                                                        queue:dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)
                                                      options:@{CBCentralManagerOptionShowPowerAlertKey:[NSNumber numberWithBool:YES]}];

 _peripheralManager = [[CBPeripheralManager alloc] initWithDelegate:self
                                                               queue:dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)
                                                             options:@{CBCentralManagerOptionShowPowerAlertKey:[NSNumber numberWithBool:YES]}]; 

//My characteristic and service setup is here and I finally add them to the peripheral: 
[_peripheralManager addService:transferService];
[_peripheralManager addService:anotherService];

然后我按如下方式启动外围管理器广告和中央扫描:

[self.peripheralManager startAdvertising:@{CBAdvertisementDataLocalNameKey : @"My name",
                                           CBAdvertisementDataServiceUUIDsKey : @[[CBUUID UUIDWithString:my_UUID]] }];

[self.centralManager scanForPeripheralsWithServices:@[[CBUUID UUIDWithString:SAME_UUID_AS_ABOVE]]
                                              options:nil];

在这一点上委托方法:

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

被调用,广告数据字典与我在init方法中执行的设置一致,但是当我到didDiscoverServices时,我看不到外围设备的任何服务。我已经在控制台中检查过,指针是相同的(我将外围设备存储在属性中),UUID也是如此。一个有趣的观点是,当我第一次发现外围设备时,名称是正确的,例如

<CBPeripheral: 0x1700f8500, identifier = xxxxx, name = My Name, state = disconnected>

但是当它进入didDiscoverServices时 - <CBPeripheral: 0x1700f8500, identifier =xxxx, name = iPhone, state = connected>

请注意名称的不同。

我尝试将外设和中心设置为不同的队列而没有结果。我的问题是,是否可以同时使用外围设备和中央设备,这可能会在发现服务时出现问题?

编辑:另一种奇怪。 1.如果我重新启动两个设备,则在广告和扫描的呼叫之间在6 Plus上添加sleep呼叫我可以从4S看到该服务。 2.如果我删除sleep并再次运行应用程序,我仍然可以看到该服务。但是,当我将4S插入Xcode并试图从那里驱动流量时 - 我似乎无法得到它。 4S的后续尝试也失败了。

3 个答案:

答案 0 :(得分:1)

与在外围设备完全插入之前添加服务相关的类似问题。我发现在peripheralManagerDidUpdateState:委托方法中添加服务是添加服务的好地方,因为这是在外围设备被调用后立即调用的。

答案 1 :(得分:0)

问题在于我是在初始化之后立即将服务添加到外围设备管理器,即状态完成块没有。

答案 2 :(得分:0)

你应该检查:

(void)peripheralManagerDidUpdateState:(CBPeripheralManager *)peripheral { 
    if (self.manager.state >= CBPeripheralManagerStatePoweredOn) { 
        [self.manager addService:self.service]; 
    }
    else {
        [self.manager removeService:self.service];
    }
}

这将确保您在打开BLE时添加服务,并在关闭服务时将其删除。