CoreBluetooth用字节数组写入数据

时间:2016-02-18 11:56:23

标签: ios arrays swift byte

我目前正在尝试使用corebluetooth从中心向外围设备发送7bytes的数据,我的代码如下:

func peripheral(peripheral: CBPeripheral, didDiscoverCharacteristicsForService service: CBService, error: NSError?) {

connectingPeripheral = peripheral
for characteristic in service.characteristics as [CBCharacteristic]!{ 

if characteristic.UUID.UUIDString == "2AF2"{
    connectingCharacteristicWrite = characteristic
}

@IBAction func Button(sender: UIButton) {
    let value: [UInt8] = [0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07]
    let data = NSData(bytes: value, length: 7)
    peripheral.setNotifyValue(true, forCharacteristic: characteristic)
    connectingPeripheral.writeValue(data, forCharacteristic: connectingCharacteristicWrite, type: CBCharacteristicWriteType.WithoutResponse)
}

但我只能发送一个字节。我尝试了以下代码行:

let value: [UInt8] = [0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07]
let data = NSData(bytes: value, length: 7)
connectingPeripheral.writeValue(data, forCharacteristic: connectingCharacteristicWrite, type: CBCharacteristicWriteType.WithResponse)

但仍无法发送数据。有谁知道为什么?

2 个答案:

答案 0 :(得分:0)

试试这个:

let value: [UInt8] = [0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07]
let data = NSData(bytes: value, length: 7)

答案 1 :(得分:0)

这是Swift 4

的略微修改的解决方案
let value: [UInt8] = [0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07]
connectingPeripheral.writeValue(Data(bytes: value), for: connectingCharacteristicWrite, type: .withResponse)