Search code examples
objective-cswiftcore-bluetoothnrf51dfu

Convert Objective-C code to Swift


I have been working with nrf51x. I have a sample code written in Obj-C. I was not able to convert it to Swift.

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

I tried

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)

and this one

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

Can any one help me? Thank you very much


Solution

  • Thanks to @Robert answer I was able to find a solution. I finally created a method that writes an array of [UInt8] to a CBCharacteristic. Here is the code:

    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)
    }