Hi guys I need to write a value from my iPhone to an BLE peripheral.
The service and characteristic is discovered and the connection is also there.
PROBLEM: I need to write the value 2 to the characteristic. For that I call
peripheral.writeValue(data, forCharacteristic: characteristic,
type: CBCharacteristicWriteType.WithResponse)
data should be 2 but it should be from Type NSData. My conversion from int to NSData has the result 02000000 and not 2, the characteristic needs 2.
What is wrong in this conversion? How can I get NSData with value 2
var ring = 2
//Convert 2 to NSData -> for peripheral.writeValue()
let data = NSData(bytes: &ring, length: sizeof(NSInteger))
//---> let data is <02000000> should be <2>
print(data)
The following Code is context where I need the value 2 in NSData
func peripheral(peripheral: CBPeripheral, didUpdateValueForCharacteristic characteristic: CBCharacteristic, error: NSError?) {
var data1 = characteristic.descriptors
//print("\(data1.dynamicType)")
//print(data1)
var ring = 2
//Convert 2 to NSData -> for peripheral.writeValue()
let data = NSData(bytes: &ring, length: sizeof(NSInteger))//sizeof(NSInteger))
//---> let data is <02000000> should be <2>
print(data)
//Write Datat to peripheral ( characteristic )
peripheral.writeValue(data, forCharacteristic: characteristic, type: CBCharacteristicWriteType.WithResponse)
}
func peripheral(peripheral: CBPeripheral, didWriteValueForCharacteristic characteristic: CBCharacteristic, error: NSError?) {
print("Value is Written")
}
Thank you a lot.