2

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.

Tim
  • 21
  • 1
  • Please clarify your specific problem or provide additional details to highlight exactly what you need. As it's currently written, it's hard to tell exactly what you're asking. – Community Jul 20 '23 at 18:42
  • 2
    Given your example, you'd move your call to `saveDevice` into `parseResponse`. Is there something more to the question? There's nothing related to `async` or to completion handlers here. Just do your operation when the notification comes in. – Rob Napier Jul 20 '23 at 22:42

0 Answers0