How to Disconnect CoreBluetooth Peripheral cleanly in Swift


To disconnect a connected peripheral in CoreBluetooth we call method cancelPeripheralConnection


This did disconnect peripheral in CoreBluetooth. In my program there is code that caches old discovered peripherals for certain period. It does go through cached peripherals to search for their services. What I found was that even if peripheral was disconnected code was somehow discovering the services and characteristics. There is a segment of code which is written to trigger certain behaviour when characteristics of peripheral is discovered. I did not want this for disconnected peripherals. Problem is not an issue for there are very simple solution for this scenario like checking the state of peripherals before trigger and etc.

I am emphasizing that Disconnected peripheral’s services still can be discovered in CoreBluetooth. Which is not an issue. I had assumed that when peripheral gets disconnected it removes its services and characteristics.

These methods do get called up even if peripheral is no more connected.

func peripheral(_ peripheral: CBPeripheral, didDiscoverServices error: Error?)
func peripheral(_ peripheral: CBPeripheral, didDiscoverCharacteristicsFor service: CBService, error: Error?)

For some reason If we want to remove the services and characteristics then we can remove services from peripheral after disconnection. Now further more If we want to remove our advertisement data also of peripheral on disconnection then we should handle that too. We are talking about cleanly disconnecting peripheral.


It may be confusing but here my app is both central and peripheral. In this case when I disconnect session from CoreBluetooth, I am disconnecting my device from any existing connected peripheral and also cleaning up services and advertisement data of my device.

You might also like: How to Send Local Video to iMessage in Swift

You might also like: AVAudioPlayer not playing any sound

You might also like: How to Get Substring With NSRange in Swift 5

You might also like: Adding two numbers in macOS x86-64 Assembly - Part 2

More Articles

Recommended posts