1

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

Zied Feki
  • 812
  • 1
  • 10
  • 19

2 Answers2

0

The class below builds without error. I am using 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)
    }
}
Verticon
  • 2,419
  • 16
  • 34
0

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)
}
Zied Feki
  • 812
  • 1
  • 10
  • 19