将Objective-C代码转换为Swift



我一直在使用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))

有人能帮我吗?非常感谢

下面的类构建时没有出现错误。我使用的是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)
    }
}

感谢@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)
}

最新更新