大家好我需要从iPhone写一个值到BLE外设。
发现了服务和特征,并且也存在连接。
问题: 我需要将值2写入特征。 为此,我打电话给
peripheral.writeValue(data, forCharacteristic: characteristic,
type: CBCharacteristicWriteType.WithResponse)
数据应为2,但应该来自Type NSData。 我从int到NSData的转换结果为 02000000 而不是 2 ,特征需要2。
转换有什么问题?如何获得值 2
的NSData 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)
以下代码是我需要NSData中值2的上下文
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")
}
非常感谢你。