iOS Core Bluetooth:获得API MISUSE警告

53

我正在使用Core Bluetooth API编写iOS 7的测试应用程序。在测试应用程序时,我发现我正在收到以下警告消息:

TestBluetooth[626:60b] CoreBluetooth[API MISUSE]只有在开启状态下才能接受命令

后来我调试了应用程序并发现,警告消息是来自以下代码行:

[manager scanForPeripheralsWithServices:array options:scanOptions];

有没有人能告诉我为什么我在控制台中收到这条消息?

周围有蓝牙4.0的Android设备,但此应用程序未将其发现为外设。那么为什么它无法将蓝牙4.0 LE Android设备发现为外设呢?


2
在执行操作之前,您需要检查CBCentralManagerstate属性:https://developer.apple.com/library/ios/documentation/CoreBluetooth/Reference/CBCentralManager_Class/translated_content/CBCentralManager.html#//apple_ref/occ/instp/CBCentralManager/state - Larme
对于那些尝试解决Flutter(flutter_blue_plus包)中相同问题并在这里寻找线索的人来说,你需要为蓝牙状态设置一个流订阅。 - Shawn Ashton
4个回答

83
你必须等待[-CBCentralManagerDelegate centralManagerDidUpdateState:]回调被调用后,再验证状态是否为PoweredOn,然后才能开始扫描外围设备。

1
我已经创建了一个工具来帮助调试API误用错误:https://github.com/nrbrook/NBCoreBluetoothAPIMisuseGuard - Nick

4
请使用以下代码解决警告:
(您可以参考 https://github.com/luoxubin/BlueTooth4.0 中的代码)
if (bluetoothPowerOn) {
    [self.centralManager scanForPeripheralsWithServices:[serviceIDs copy] options:@{CBCentralManagerScanOptionAllowDuplicatesKey:@(NO)}];
}

-(void)centralManagerDidUpdateState:(CBCentralManager *)central{

    switch (central.state) {

        case CBManagerStatePoweredOn:
        {
            bluetoothPowerOn = YES;    //new code
            [self start];
            break;
        }

        default:
        {    
            bluetoothPowerOn = NO;   //new code
            [self stopScan:[NSError hardwareStatusErrorWithMessage:@"Cannot open Bluetooth, please check the setting." hardwareStatus:central.state]];    
            break;
        }
    }
}

3

蓝牙开启时进行扫描:

func centralManagerDidUpdateState(_ central: CBCentralManager) {
        switch central.state {
        case .unknown:
            print("unknown")
        case .resetting:
            print("resetting")
        case .unsupported:
            print("unsupported")
        case .unauthorized:
            print("unauthorized")
        case .poweredOff:
            print("poweredOff")
            centralManager?.stopScan()
        case .poweredOn:
            print("poweredOn")
            centralManager?.scanForPeripherals(withServices: nil, options: nil)
        }
    }

-1
打开iPhone的蓝牙可以解决我的问题。打开蓝牙后不再收到以下警告: CoreBluetooth[API MISUSE] can only accept commands while in the powered on state

这并没有回答问题。一旦您拥有足够的声望,您将能够评论任何帖子;相反,提供不需要询问者澄清的答案。- 来自审核 - CodeChanger

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接