Ios <;错误>;:[CoreBluetooth]API误用:取消未使用外设的连接
我的设想:Ios <;错误>;:[CoreBluetooth]API误用:取消未使用外设的连接,ios,objective-c,core-bluetooth,Ios,Objective C,Core Bluetooth,我的设想: 我用sigkill()->将我的应用程序置于后台 数据从BT设备发送,并在调用centralManager:willRestoreState:时成功连接 连接设备后,我将BT设备移出应用程序范围,并调用方法centralManager:didDisconnectPeripheral:error:,错误代码为6。 我尝试通过调用[\u centralManager connectPeripheral:peripheral options:nil]重新连接外围设备,然后出现以下错误: [
sigkill()
->将我的应用程序置于后台centralManager:willRestoreState:
时成功连接centralManager:didDisconnectPeripheral:error:,错误代码为6。
[\u centralManager connectPeripheral:peripheral options:nil]
重新连接外围设备,然后出现以下错误:此错误是什么意思?正如消息所示,您需要将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,以便在重新启动应用程序时尝试建立连接ID,如中所述
最后,有几个关于参考文献的链接:
在“强引用和弱引用”上进行搜索将产生额外的结果。如果您使用的是ARC,那么简单地拥有一个属性将创建一个强引用。无论如何,将CBPeripheral实例添加到数组中也会创建强引用。如何创建强引用?这个答案缺乏足够的细节,不足以成为一个好答案。也许你能提供更多的信息?我很久以前就解决了这个问题(很抱歉没有给出答案)。这个答案对我很有用,我将centralManager改为一个属性。引用和内存管理本身就是一个大主题。我将尝试在下面包含一些有用的链接。抱歉,无法编辑我的评论。我已经更新了答案以包含更多信息。如果你想进一步澄清,请告诉我。