Reputation: 4001
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?
Upvotes: 1
Views: 2063
Reputation: 11
I hit the same. Eventually learned that you have to set the delegate to self before making the call to discover services. Code as follows.
peripheral.delegate = self
peripheral.discoverServices(nil)
It has been 4 years since this question, hopefully becomes useful to someone.
Upvotes: 1
Reputation: 293
if this is not working
func peripheral(_ peripheral: CBPeripheral, didDiscoverServices error: Error?)
then first try to scan BLE device using BLE Scanner iOS, if in that app it shows the services then the issue in your code otherwise if BLE Scanner shows 0 service then the issue is inside the Peripheral device, or you can check the services by using print(peripheral.services) after connecting to peripheral if it print nil then discoverServices not called, other wise it call.
or you can restart your iPhone sometime data stored into cache.
Upvotes: 0
Reputation: 26036
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.
Upvotes: 1