我必须在用 Swift UI 编写的简单项目中添加 BLE 设备支持。
型号:手机发送请求(.withoutResponse)<->BLE 设备通过 BLE 通知应答。
由于我不是专业的 Swift 程序员,我的主要问题是如何通过代码解析这些通知以执行另一个函数(例如,如果响应正常,则将设备参数保存到 CoreData/UserDefaults)。
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")
}
}
}
我已经开始学习 swift 异步编程,但我不得不向你寻求帮助。
如果您要求Peripheral通信时解析数据。
这就是你尝试一下的方法。
func peripheral(_ peripheral: CBPeripheral, didUpdateValueFor characteristic: CBCharacteristic, error: Error?) {
if let error = error {
print("ERROR didUpdateValue \(error)")
return
}
//BLE_Characteristic_uuid > Your BLE Char UUID
if characteristic.uuid == CBUUID(string: BLE_Characteristic_uuid) {
guard let value = characteristic.value else { return }
let content = String(data: value, encoding:.utf8)?.trimmingCharacters(in: .whitespacesAndNewlines) ?? ""//.filter { !" \n\t\r".contains($0) } ?? ""
print("Value Received:-->",content )
if let i = content.utf8.firstIndex(where: { $0 >= 32 }) {
let asciiPrefix = String(content.utf8[..<i])!
print(asciiPrefix)
}else{
return
}
}
}
32 的 ASCII 值对应于空格字符 (' ')。因此,表达式 content.utf8.firstIndex(where: { $0 >= 32 }) 返回内容字符串的 UTF-8 表示形式中第一个非控制字符的索引。但是您可以根据您的要求控制它。
它也会忽略\u{01}