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

1.9k views Asked by At

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?

2

There are 2 answers

0
Rob Napier On

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.

0
dennis_ka On

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.
}