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.
- I was calling
startScanning()
whencentralManagerDidUpdateState()
was called withcentral.state == .poweredOn
. This causing scanning to start again right after callingmyCentral.connect(connectedPeripheral!, options: nil)
- Calling
myCentral.stopScan()
aftermyCentral.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
Is There Difference Between Using a Constructor and Using .Init
Datefromstring() Returns Incorrect Date
What Does This Mean? Variable Declared Followed by a Block Without Assignment
Store Data in Custom Class Array in Core Data
How Could I Request Text from a Website in Swift
Behavior of the Cameranode Is Unclear When Moving a 3D Model in a Scene with Scenekit
How to Use Dispatchgroup/Gcd to Execute Functions Sequentially in Swift
How to Reset a Subview in Swiftui
How to Get String from Ascii Code in Swift
Why Do We Need to Specify Init Method
Swift: Can't Edit Properties of Custom Table Cell Programmatically
Replacing Multiple Different Occurences with Multiple Different Replacements - Swift4.2
Nsurl Fail Able Initialiser Initwithstring: Does Not Return Nil on Empty String in Swift
Swiftui - Mapkit - Binding Mapkit and Show View on Annotation Callout Buttons
Decode/Encode Dictionary Keyed by Date