I have to add a BLE device support in my simple project written in Swift UI.
Model: Phone sends a request (.withoutResponse) <-> BLE Device answers by BLE notification.
As I am not a professional Swift programmer my main problem is how to parse these notifications through code to execute another function (f.e. save device parameters to CoreData/UserDefaults if Response is OK).
func saveDevice(identifier: UUID, name: String, type: Int) {
writeToIdentifier(identifier: identifier, data: Request.deviceSave(name: name, type: type))
//!
CoreDataModel.shared.saveDevice(uuid: identifier, name: name, type: Int16(type)) // I'd like to complete/or not this function when we get notification from device
}
func writeToIdentifier(identifier: UUID, data: Data) {
print("Writing to identifier: ", identifier)
if let index = self.devices.firstIndex(where: {$0.identifier == identifier}) {
let peripheral = self.devices[index].peripheral
let characteristic = peripheral.services?.first?.characteristics?[1]
peripheral.writeValue(data, for: characteristic!, type: .withoutResponse)
}
}
func peripheral(_ peripheral: CBPeripheral, didUpdateValueFor characteristic: CBCharacteristic, error: Error?) {
if let value = characteristic.value {
parseResponse(data: value, identifier: peripheral.identifier)
}
}
func parseResponse(data: Data, identifier: UUID) {
let method: UInt8 = data.first!
switch (method) {
case 1:
print("Method: DEVICE SAVE")
if (data[5] == 1) { // Here we get response and only now we'd like to save the device to CoreData
print("Is configured: true")
} else {
print("Is configured: false")
}
}
}
I have already started to learn swift asynchronous programming but I had to ask you for help.