Search code examples
iosswiftbluetoothnsdatauint8t

Convert NSString to UInt8 in a function in Swift?


I'm creating a Swift app in Xcode that sends a command to a BLE adapter in order to make the LED's connected to it change to a different colour.

As I've established from a reply to a previous post on SO, I have to send command in terms of hex integers in an array. I'm using the following code in order to do this:

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

Therefore, this requires a UInt8 form as suggested above.

However, I'm trying to use sliders as colour pickers on my Swift app in order to set the R, G, and B colours of the LED strip connected to the BLE receiver. In order to do this I have created three sliders for R, G and B respectively, setting the minimum value of each to 0 and the max to 255 (since 255 converts to FF in hex). I'm then using the following function to convert these to hex form for me to implement in the command above.

func colorToHex(input: Int) -> UInt8 {
    var st = NSString(format: "%2X", input)
    return st
}

The problem with this is the fact that I must return a UInt8 value back again. Since 'st' is an NSString, Xcode throws an error of 'NSString not convertible to UInt8'.

I'm fairly new to Swift. The question here is, how do I get the function to return a UInt8 value how do I get it to form a UInt8 value?

Any help would be greatly appreciated!


Solution

  • There is no need to use NSString or Int. If redSlider is your UISlider with minimum value 0 and maximum value 255 then you can just compute

    let redByte = UInt8(redSlider.value)
    

    and use that in your bytes array:

    var bytes : [UInt8] = [ 0x52, 0x13, 0x00, 0x56, 0xFF, 0x00, 0x00, 0x00, 0xAA ]
    bytes[0] = redByte // Assuming that the first array element is for red.