1

我一直在使用 nrf51x。我有一个用 Obj-C 编写的示例代码。我无法将其转换为 Swift。

uint8_t value = ACTIVATE_AND_RESET_REQUEST;
[self.bluetoothPeripheral writeValue:[NSData dataWithBytes:&value length:sizeof(value)] forCharacteristic:self.dfuControlPointCharacteristic type:CBCharacteristicWriteWithResponse];

我试过了

var value: UInt8 = DfuOperations.VALIDATE_FIRMWARE_REQUEST.rawValue
let ptr = UnsafePointer<Void>(value)
let data = NSData(ptr, length: sizeofValue(value))
dfuPeripheral!.writeValue(data, forCharacteristic: self.dfuControlPointCharacteristic, type: CBCharacteristicWriteType.WithResponse)

和这个

var value: UInt8 = DfuOperations.VALIDATE_FIRMWARE_REQUEST.rawValue
let data = NSData(&value, length: sizeofValue(value))

谁能帮我?非常感谢

4

2 回答 2

0

下面的类构建没有错误。我正在使用 Xcode 7.1。

import Foundation
import CoreBluetooth

class Test {
    func test(bluetoothPeripheral: CBPeripheral, dfuControlPointCharacteristic: CBCharacteristic) {
        let value = UInt8(ACTIVATE_AND_RESET_REQUEST.rawValue)
        let encodedValue = NSData(bytes: [value], length: sizeof(UInt8))
        bluetoothPeripheral.writeValue(encodedValue, forCharacteristic: dfuControlPointCharacteristic, type: CBCharacteristicWriteType.WithResponse)
    }
}
于 2015-11-07T17:14:26.320 回答
0

感谢@Robert的回答,我能够找到解决方案。我终于创建了一个将 [UInt8] 数组写入 CBCharacteristic 的方法。这是代码:

func updateValueForCharacteristic(characteristic: CBCharacteristic, value: [UInt8], writeType: CBCharacteristicWriteType = CBCharacteristicWriteType.WithResponse){
    let data = NSData(bytes: value, length: sizeofValue(value))
    dfuPeripheral!.writeValue(data, forCharacteristic: characteristic, type: writeType)
}
于 2015-11-11T11:48:02.203 回答