Diddiscoverservices Is Not Being Called After a Ble Connection

didDiscoverServices is not being called after a BLE connection

Method from the doc:

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

Yours:

func peripheral(peripheral: CBPeripheral, didDiscoverServices error: Error?)

Erase it and rewrite it letting XCode autocompletion helps you, copy/paste it from the doc, or just add a _ that is missing.

The method is optional, internally CoreBluetooth framework check if the delegates responds to the selector (respondsToSelector()) and the selector includes that "_" which yours doesn't have. So it won't match and it won't call it because it's not the same.

CoreBluetooth peripheral:didDiscoverServices not firing

You must set your object as the CBPeripheral's delegate in order to get calls to the CBPeripheralDelegate functions:

func centralManager(_ central: CBCentralManager, didConnect peripheral: CBPeripheral) {
print("Peripheral connected")
peripheral.delegate = self
let service = listOfServices.first(where: { $0.uuid == CBUUID(string:"FFF0")})
peripheral.discoverServices([(service?.uuid)!])
}

Swift BLE didDiscoverServices not executing. Am I missing something?

func peripheral(_ peripheral: CBPeripheral, didDiscoverServices error: Error?) is a CBPeripheralDelegate method.

So what you were missing is setting the CBPeripheral object delegate.

So just before doing peripheral.discoverServices([BLETemperatureService]), you need to do peripheral.delegate = self.

Can't discover any services, but can connect to device

I figured out two bugs in my code.

  1. I was calling startScanning() when centralManagerDidUpdateState() was called with central.state == .poweredOn. This causing scanning to start again right after calling myCentral.connect(connectedPeripheral!, options: nil)
  2. Calling myCentral.stopScan() after myCentral.connect(connectedPeripheral!, options: nil) was causing disconnections

I don't understand why either of those were happening, but fixing them allowed me to now connect and get services and characteristics!



Related Topics



Leave a reply



Submit