ios - <错误> : [CoreBluetooth] API MISUSE: Cancelling connection for unused peripheral

标签 ios objective-c core-bluetooth

我的场景:

  1. 我用 sigkill() 终止了我的应用程序 -> 应用程序进入后台。
  2. 数据从 BT 设备发送,并在调用 centralManager: willRestoreState: 时成功连接。
  3. 连接设备后,我将 BT 设备移出应用程序范围,方法 centralManager: didDisconnectPeripheral: error: 被调用,错误代码为 6。
  4. 我尝试通过调用 [_centralManager connectPeripheral:peripheral options:nil] 重新连接外围设备,然后出现以下错误:

[CoreBluetooth] API MISUSE: Cancelling connection for unused peripheral , Did you forget to keep a reference to it?

这个错误是什么意思?

最佳答案

正如消息所暗示的那样,您需要将 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 中所述。

最后,一些关于引用的链接:

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

关于ios - <错误> : [CoreBluetooth] API MISUSE: Cancelling connection for unused peripheral,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34837148/

相关文章:

ios - 使用 unwind segue 发送值

ios - 在 UITabBar 中启动 Storyboard View

objective-c - CBperipheral uuid 在 i-phone5 上的 ios 6.0.1 中为空

ios - Xcode5无法安装SDK6

ios - 从另一个 View 添加注释到 map

iphone - 从另一个选项卡重新加载 UITableView

iphone - 将 NSString 转换为 Int

ios - 异步调用中的推特分享错误

ios - CBPeripheral 对象的名称始终为 nil 值并且处于断开状态

swift - 符合 'CBCentralManagerDelegate'协议(protocol)