BensTechTips BensTechTips - 1 year ago 1762
Swift Question

Sending Hex String using WriteValue in Swift

I've been creating an app using XCode and Swift to connect to a bluetooth device (that has a LED colour strip connected to it) and I have written a piece of code that will make it change colour.

Using a bluetooth sniffer, I know that I need to send the value of '52130056FF000000AA' which would make it change to red, in this example. Here's a snippet of the code I have already. Characteristicx is defined before this code.

let data: NSData = "52130056FF000000AA".dataUsingEncoding(NSUTF8StringEncoding)!
peripheral.writeValue(data, forCharacteristic: characteristicx, type: CBCharacteristicWriteType.WithoutResponse)

This code converts the hex string given to this, which I do not want to send.
'<35323133 30303536 46463030 30303030 4141>'

So, the question is, How do I get Swift to send just the 52130056FF000000AA to the BLE device and not the converted string? The issue here is that the writeValue command requires NSData (as far as I can see) and I'm not sure how to use a plain hex string as the data to send in NSData form.

Hope someone can help with this! Any help or even suggestions would be greatly appreciated.

Answer Source

If you don't insist on using a hex string then the easiest solution would be to create the data from an array with hex integer values:

let bytes : [UInt8] = [ 0x52, 0x13, 0x00, 0x56, 0xFF, 0x00, 0x00, 0x00, 0xAA ]
let data = NSData(bytes: bytes, length: bytes.count)