I am working with CoreBluetooth to connect to a BLE device. I want to verify if the device is already paired before performing certain actions. I followed the steps mentioned in this StackOverflow post, but I am facing an issue. Even though my device gets paired successfully, the didWriteValueFor delegate method is not being called.
Here is what I have done so far:
- Scanning and Connecting:
I scan for peripherals and connect to them successfully. - Discovering Services and Characteristics:
I discover the services and characteristics of the connected peripheral. - Writing to a Characteristic:
I attempt to write to a characteristic after ensuring that the device is paired.
Despite these steps, the didWriteValueFor method is not invoked. I’m sure the device is paired correctly. How can I reliably determine if a device is paired, and what could be causing didWriteValueFor not to be called?
class BluetoothManager: NSObject, CBCentralManagerDelegate, CBPeripheralDelegate {
private var centralManager: CBCentralManager!
private var connectedPeripheral: CBPeripheral?
override init() {
super.init()
centralManager = CBCentralManager(delegate: self, queue: nil)
}
func centralManagerDidUpdateState(_ central: CBCentralManager) {
if central.state == .poweredOn {
centralManager.scanForPeripherals(withServices: nil, options: nil)
}
}
func centralManager(_ central: CBCentralManager, didDiscover peripheral: CBPeripheral, advertisementData: [String : Any], rssi RSSI: NSNumber) {
connectedPeripheral = peripheral
connectedPeripheral?.delegate = self
centralManager.connect(peripheral, options: nil)
}
func centralManager(_ central: CBCentralManager, didConnect peripheral: CBPeripheral) {
connectedPeripheral?.discoverServices()
peripheral.discoverServices(nil)
}
func peripheral(_ peripheral: CBPeripheral, didDiscoverServices error: Error?) {
guard let services = peripheral.services else { return }
for service in services {
peripheral.discoverCharacteristics(nil, for: service)
}
}
func peripheral(_ peripheral: CBPeripheral, didDiscoverCharacteristicsFor service: CBService, error: Error?) {
let value = 1234
let data = withUnsafeBytes(of: value) { Data($0) }
for characteristic in service.characteristics!
{
if characteristic.properties.contains(.notify) {
peripheral.setNotifyValue(true, for: characteristic)
peripheral.writeValue(data, for: characteristic, type: .withResponse)
}
}
}
func peripheral(_ peripheral: CBPeripheral, didWriteValueFor characteristic: CBCharacteristic, error: Error?) {
if let error = error {
print("Error writing value: (error.localizedDescription)")
} else {
print("Successfully wrote value to (characteristic.uuid)")
}
}
}
2