我的场景:
- 我用
sigkill()
终止了我的应用程序 -> 应用程序进入后台。 - 数据从 BT 设备发送,并在调用
centralManager: willRestoreState:
时成功连接。 - 连接设备后,我将 BT 设备移出应用程序范围,方法
centralManager: didDisconnectPeripheral: error: 被调用,错误代码为 6。
- 我尝试通过调用
[_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/