我正在开发一个应用程序,该应用程序需要从 ble 设备获取数据以显示在应用程序上,为了从 ble 设备获取数据,我必须编写某些命令,如 NUM_QUEUE、READ_ALL 等。所以我卡在这里一起执行所有命令,我做什么我是否将所有命令分配到一个数组中,并通过获取每个命令在循环中执行写入函数,但是当我读取值时,我只得到了数组中最后一个命令的值。请帮我读取所有命令的所有值,有什么在数组中写入命令时出错。请帮助。
这是我要写的代码
func peripheral(_ peripheral: CBPeripheral, didDiscoverCharacteristicsFor service: CBService, error: Error?) {
if let characterArray = service.characteristics as [CBCharacteristic]? {
for cc in characterArray {
myCharacteristic = cc
peripheral.readValue(for: cc)
peripheral.setNotifyValue(true, for: myCharacteristic)
writeValue()
}
}
}
func writeValue() {
if isMyPeripheralConected { //check if myPeripheral is connected to send data
let arrayCommands = ["NUM_QUEUE\r","READ_ALL\r"]
for i in 0...arrayCommands.count-1 {
let dataToSend: Data = arrayCommands[i].data(using: String.Encoding.utf8)!
myBluetoothPeripheral.writeValue(dataToSend, for: myCharacteristic, type: CBCharacteristicWriteType.withResponse)
}
} else {
print("Not connected")
}
}