'Core Bluetooth. How can I check does peripheral already connect?

During development I got a problem witch related to the connection central and peripheral. When one of the central already connected with perepheral I have to don't allow to connect other central. Maybe someone nows how can I check does the peripheral already connected?



Solution 1:[1]

If you simply want to know whether a peripheral is connected to a central, then you can simply check its state. You can do this immediately during discovery.

public func centralManager(_ central: CBCentralManager, didDisconnectPeripheral peripheral: CBPeripheral, error: Error?) {
     guard peripheral.state == .disconnected else { return }
     // Peripheral is not connected to any central.
}

Solution 2:[2]

Call retrieveConnectedPeripherals(withServices:) to get a list of currently-connected peripherals for a given list of service UUIDs. These are connected to the phone, not to your app. You still need to call connect to connect them the currently running app (exactly like you would if you discovered them). This call is synchronous, since the OS already knows all the connected devices and can just return them.

Typically this list is empty. The most common production reason for it to be non-empty is that another app has connected to the device (LightBlue or some other Bluetooth scanner for example). During development, however, it is very common that the app gets killed, and in that case the phone may not have dropped the connection yet when you relaunch the app, and this will handle that situation.

While you can scan for all devices by passing nil to scanForPeripherals, there is no equivalent way to retrieve "all connected devices" You must list the desired service UUIDs. I don't believe this should be a problem in your case.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 dennis_ka
Solution 2