I am a little confused on how Data object works in swift. I am attempting to write values using bluetooth and one of the values I need to write is 500. In order to write you need to convert the value to a data object before sending. Here's the code I am using.
if(characteristic != nil){
var byteCount = 1
if(sensitivity > 255){
byteCount = 2
}
let data = Data.init(bytes: &sensitivity, count: byteCount)
peripheral.writeValue(data, for: sensCharacteristic!, type: CBCharacteristicWriteType.withResponse)
peripheral.readValue(for: sensCharacteristic!)
}else{
print("No bluetooth Connection")
}
From what I understood if I try to send a value that takes more than a byte to represent then it will overflow, thus when I send 500 the value it writes is actually 244. Because of this I tried writing and sending 2 bytes but the value I am getting is 244101. I am unsure where that value is coming from. What is the correct way to covert 500?
This function is called whenever a characteristic is read and then placed in a label. All it does is loop through the data and adds each byte to a string.
func readCharacteristic(data: Data) -> String {
var characterString = ""
for byte in data {
let c = String(byte)
characterString.append(c)
}
return characterString
}