【问题标题】:<Error>: [CoreBluetooth] API MISUSE: Cancelling connection for unused peripheral<错误>:[CoreBluetooth] API MISUSE:取消未使用外围设备的连接
【发布时间】:2016-04-22 14:04:23
【问题描述】:

我的场景:

  1. 我用 sigkill() 杀死了我的应用程序 -> 应用程序进入后台。
  2. 数据从 BT 设备发送并成功连接,同时调用 centralManager: willRestoreState:
  3. 连接设备后,我将BT设备从应用程序范围中取出,方法centralManager: didDisconnectPeripheral: error: is invoked with error code 6.
  4. 我尝试通过调用[_centralManager connectPeripheral:peripheral options:nil] 重新连接外围设备,然后我收到以下错误:

[CoreBluetooth] API MISUSE:取消未使用的连接 外围设备,你忘记保留它的引用了吗?

这个错误是什么意思?

【问题讨论】:

    标签: ios objective-c core-bluetooth


    【解决方案1】:

    正如消息所暗示的,您需要将 CBPeripheral 实例存储在对其保持强引用的位置。

    通常,通过将指针存储在某处,您可以对对象进行强引用。例如,您可能有一个 BluetoothConnectionManager 保存已连接外围设备的列表:

    @implementation BluetoothConnectionManager
    - (instancetype)init
    {
        if(self = [super init])
        {
            _knownPeripherals = [NSMutableArray array];
            dispatch_queue_t centralQueue = dispatch_queue_create("com.my.company.app", DISPATCH_QUEUE_SERIAL);
            _centralManager = [[CBCentralManager alloc] initWithDelegate:self queue:centralQueue options:@{CBCentralManagerOptionShowPowerAlertKey : @YES}];
        }
        return self;
    }
    
    - (void)centralManager:(CBCentralManager *)central
      didConnectPeripheral:(CBPeripheral *)peripheral
    {
        [_knownPeripherals addObject:peripheral];
    }
    
    - (void)centralManager:(CBCentralManager *)central
    didDisconnectPeripheral:(CBPeripheral *)cbPeripheral
                     error:(NSError *)error
    {
        // This probably shouldn't happen, as you'll get the 'didConnectPeripheral' callback
        // on any connected peripherals and add it there.
        if(![_knownPeripherals containsObject:cbPeripheral])
        {
            [_knownPeripherals addObject:cbPeripheral];
        }
    
        [_centralManager connectPeripheral:cbPeripheral options:nil];
    }
    
    @end
    

    或者您可以修改此代码以引用单个连接的外围设备。

    您还可以使用它写出您之前的连接 ID,以便在重新启动应用程序时尝试建立它们,如 Apple Docs 中所述

    最后,一些参考链接:

    搜索“强引用和弱引用 ios”会产生额外的结果。如果您使用 ARC,只需拥有一个属性即可创建一个强引用。无论如何,将 CBPeripheral 实例添加到数组也会创建一个强引用。

    【讨论】:

    • 如何创建强引用?
    • 这个答案缺乏足够的细节来真正成为一个好的答案。也许您可以提供更多信息?
    • 我很久以前就解决了这个问题(很抱歉没有发布答案)。这个答案对我有用,我将 centralManager 更改为一个属性。
    • 引用和内存管理本身就是一个很大的话题。我会尝试在下面添加一些有用的链接。
    • 抱歉,无法编辑我的评论。我已经更新了答案以包含更多信息。如果您需要进一步说明,请告诉我。
    猜你喜欢
    • 2017-02-28
    • 2013-10-13
    • 2016-11-08
    • 1970-01-01
    • 1970-01-01
    • 2016-05-03
    • 1970-01-01
    • 1970-01-01
    • 2013-07-21
    相关资源
    最近更新 更多