大家好,我需要将我的 iPhone 中的值写入 BLE 外围设备。
发现了服务和特征,并且连接也在那里。
问题:我需要将值 2 写入特征。为此我打电话
peripheral.writeValue(data, forCharacteristic: characteristic,
type: CBCharacteristicWriteType.WithResponse)
数据应该是 2 但它应该来自 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")
}
十分感谢。