I'm working with a BLE device which I need to verify. The BLE code I'm using is below
//Pragma Bluetooth Methods
func centralManagerDidUpdateState(_ central: CBCentralManager) {
if central.state == .poweredOn {
central.scanForPeripherals(withServices: nil, options: nil)
} else {
print("Bluetooth not available.")
}
}
func centralManager(_ central: CBCentralManager, didDiscover peripheral: CBPeripheral, advertisementData: [String : Any], rssi RSSI: NSNumber){
if let peripheralName = advertisementData[CBAdvertisementDataLocalNameKey] as? String {
if peripheralName == "test-device1" {
self.manager.stopScan()
self.peripheral = peripheral
self.peripheral.delegate = self
self.manager.connect(peripheral, options: nil)
}
}
}
func centralManager(_ central: CBCentralManager, didConnect peripheral: CBPeripheral) {
peripheral.discoverServices(nil)
}
private func peripheral(peripheral: CBPeripheral, didDiscoverServices error: Error?) {
for service in peripheral.services! {
let thisService = service as CBService
if service.uuid == SERVICE_UUID {
peripheral.discoverCharacteristics(
nil,
for: thisService
)
}
}
}
The process follows the anticipated route by passing through didDiscover and verifying the name as 'test-device1'. However, although it goes through the didConnect method and runs peripheral.discoverServices(nil) it never reaches the didDiscoverServices method. I've stepped through it several times and it always stops at didConnect().
What am I missing?
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.