didDisconnectPeripheral:没有被调用

didDisconnectPeripheral: not getting called

我有一个自定义对象 BLEDevice,它具有对 CBPeripheral 对象的弱引用。我维护了一个字典,用于保存外围设备和我的自定义对象之间的关联:

- (void)setDeviceForPeripheral:(CBPeripheral *)peripheral {
    // New device: sets a new 'BLEDevice' instance
    BLEDevice *new = [[BLEDevice alloc] initWithPeripheral:peripheral];
    new.name = peripheral.name;
    new.peripheral.delegate = self;
    [associations setObject:new forKey:peripheral];
}

当我在附近发现一个新的外围设备时,我执行以下操作:

- (void)centralManager:(CBCentralManager *)central didDiscoverPeripheral:(CBPeripheral *)peripheral advertisementData:(NSDictionary<NSString *,id> *)advertisementData RSSI:(NSNumber *)RSSI {
    if (![associations objectForKey:peripheral]) {
        NSLog(@"Found peripheral: %@", peripheral.name);
        [self setDeviceForPeripheral:peripheral];
        [[NSNotificationCenter defaultCenter] postNotificationName:@"BLEDeviceFound" object:nil];
    }
}

此时,我定义了一个自定义方法来连接到我的设备:

- (void)connect:(BLEDevice *)device {
    // Connects with the peripheral
    [manager connectPeripheral:device.peripheral options:nil];
}

这里一切正常:我的外围设备已连接,我开始在委托方法中对服务和特性执行操作 centralManager:didConnectPeripheral:

现在我的麻烦来了。当我想断开与外围设备的连接时,我执行以下操作:

- (void)disconnect:(BLEDevice *)device {
    // Unsubscribes from all the characteristics in services
    for (CBService *service in device.peripheral.services) {
        for (CBCharacteristic *characteristic in service.characteristics)
            [device.peripheral setNotifyValue:NO forCharacteristic:characteristic];
    }
    [manager cancelPeripheralConnection:device.peripheral];
}

当我调用这个方法时,我的外围设备确认断开连接成功。无论如何,委托方法 centralManager:didDisconnectPeripheral: 没有被调用。有人可以解释一下为什么吗?

正如其名称所示,当您断开外围设备时不会调用该方法。你想要的是以下内容。

- centralManager:didDisconnectPeripheral:error:

文档说:

Invoked when an existing connection with a peripheral is torn down.

当您断开外围设备时,将调用委托方法。

我发现解决方案非常简单。我只是调用了错误的委托方法。正确的签名是

- (void)centralManager:(CBCentralManager *)central didDisconnectPeripheral:(CBPeripheral *)peripheral error:(NSError *)error.

这个狗屎几周以来一直让我发疯!