【问题标题】:CoreBluetooth - didDiscoverPeripheral never called for specific serviceUUIDs but works for nilCoreBluetooth - didDiscoverPeripheral 从未调用特定的 serviceUUID,但适用于 nil
【发布时间】:2018-01-01 19:42:29
【问题描述】:

我正在扫描蓝牙设备。为此我使用CBCentralManager,就像这样

- (void)startScanning
{
    [self.centralManager scanForPeripheralsWithServices:nil options:@{ CBCentralManagerScanOptionAllowDuplicatesKey : @YES }];
}

- (void)centralManager:(CBCentralManager *)central
 didDiscoverPeripheral:(CBPeripheral *)peripheral
     advertisementData:(NSDictionary *)advertisementData
                  RSSI:(NSNumber *)RSSI
{
    NSLog(@"\n%@, rssi: %@", peripheral.identifier.UUIDString, RSSI);
    // do stuff
}

我正在使用 Estimote 应用程序在其他设备上模拟 Beacon。控制台输出如下所示:

2017-07-26 14:43:56.711830 ExampleApplication[445:55698] 外围设备:
6A3E0CB4-74BB-4472-98AA-0C9DEB1D4551,RSSI:-28

到目前为止一切都很好。

现在,我还想在应用处于后台时扫描蓝牙设备。为此,我将此类属性添加到Info.plist

<key>UIBackgroundModes</key>
<string>bluetooth-central</string>

另外,我读到当将nil 传递为serviceUUIDs 时,无法在后台扫描蓝牙设备,因此我将之前发现的外围设备的 UUID 传递给CBCentralManager

CBUUID *uuid = [CBUUID UUIDWithString:@"6A3E0CB4-74BB-4472-98AA-0C9DEB1D4551"];
[self.centralManager scanForPeripheralsWithServices:@[uuid] options:options];

还有一个问题——didDiscoverPeripheral 不再被调用,即使应用程序处于前台也是如此。是什么原因?我使用之前发现的设备的 UUID 没有问题,但不是。有什么想法吗?

【问题讨论】:

  • 您需要扫描外围设备正在通告的服务的 uuid,而不是外围设备的 uuid。外围设备的 uuid 可以改变,不同的 iOS 设备会看到同一个外围设备的不同 uuid,但服务外围设备是一致的。
  • 问题是我收到的任何外设,services 属性都是空的
  • @mag_zbc 如果你的外设没有在它的广告中加入一些服务(通过给它的服务 UUID),你不能专门扫描它,因为如果它没有做广告,您需要连接并扫描其服务。

标签: ios objective-c core-bluetooth cbcentralmanager


【解决方案1】:

iBeacons,如果它们不宣传任何其他服务,则无法使用 Core Bluetooth 在后台进行扫描。它们只能使用核心位置进行扫描。

【讨论】:

    【解决方案2】:
    -(void)centralManagerDidUpdateState:(CBCentralManager *)central {
    
    if (central.state != CBCentralManagerStatePoweredOn) {
        return;
    }
    if (central.state == CBCentralManagerStatePoweredOn) {
        [_centralManager scanForPeripheralsWithServices:@[[CBUUID UUIDWithString:@"0x180A"]] options:@{CBCentralManagerScanOptionAllowDuplicatesKey : @YES}];
        NSLog(@"Start scanning");
    }
    }
    

    你可以这样检查。它可以帮助您找出问题所在

    编辑:

    好吧,如果您尝试过上面的代码。

    那么理想的方法是在 swift 中使用新代码,因为不推荐使用 scanForPeripheralsWithServices。

    使用:类似这样的东西来检查 func scanForPeripherals(withServices serviceUUIDs: [CBUUID]?, 选项:[字符串:任何]? = 无)

    否则,您的硬件现在可能是正确的或广播正确。

    【讨论】:

    • 设备信息 org.bluetooth.service.device_information 0x180A
    • 我已经检查过了。它并没有解释为什么我可以在将nil 传递为serviceUUIDs 时很好地发现外围设备
    猜你喜欢
    • 2014-12-14
    • 2014-09-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-12-19
    • 1970-01-01
    • 2017-08-01
    • 2021-08-01
    相关资源
    最近更新 更多