Search code examples
iosarraysswiftbluetooth-lowenergyuint8array

What is the best way to modify a [UInt8] byte array in swift 4?


Hi I know many of you already know how it can be done but please help me as I'm a beginner to swift programming.

Please consider this code and help me with changes,

//My read code

let ReceiveData = rxCharacteristic?.value
        if let ReceiveData = ReceiveData {
            let ReceivedNoOfBytes = ReceiveData.count
            myByteArray = [UInt8](repeating: 0, count: ReceivedNoOfBytes)
            (ReceiveData as NSData).getBytes(&myByteArray, length: ReceivedNoOfBytes)
            print("Data Received ",myByteArray)
               }

//Now I'm storing them into some local variables like below

let b0 = myByteArray[0]
let b0 = myByteArray[1]
let b2 = myByteArray[2]
let b3 = myByteArray[3]

//Now I want to insert some data which are coming from a Textbox

var tb1 = textbox1.text
var b1 = tb1.flatMap{UInt8(String($0))}

var tb2 = textbox2.text
var b2 = tb2.flatMap{UInt8(String($0))}

//Now I'm writing all data using a function block like below

let Transmitdata = NSData(bytes: bytes, length: bytes.count)
                peripheral.writeValue(Transmitdata as Data, for: txCharacteristic!, type: CBCharacteristicWriteType.withoutResponse)
                print("Data Sent",Transmitdata)

Here I'm currently creating a new byte array under class declaration and assigning the received byte array. Like below

class Example:UIViwecontroller{

var storebytes: [UInt8]()


func somefunc(){

storebytes = myByteArray

}

And then try swapping my textbox data in the place of the first two positions in myByteArray and then pass it to transmitdata.

Is there any simple way of doing it? Like just insert bytes in places I need and then pass it to the transmit?

I have tried using some method like

bytes.insert(new data,at: index)

but it gives me an index out of range. Does someone know a better method how to do it?


Solution

  • In Swift 3+ Data can be used as a collection type containing UInt8 objects.

    Having a Data object from a String

    let hello = Data("hello".utf8)
    

    you can convert it to [UInt8] simply with

    let hello1 = [UInt8](hello)
    

    and back to Data

    let hello2 = Data(hello1)
    

    Data provides all manipulation API like append, insert, remove


    Actually you don't need [UInt8]. Given two strings as Data objects

    var hello = Data("Hello !".utf8)
    let world = Data("world".utf8)
    

    You can insert world in hello

    hello.insert(contentsOf: world, at: 6)
    print(String(data: hello, encoding: .utf8)!) // "Hello world!"
    

    And then get a range of data

    let rangeOfWorld = Data(hello[6...11])
    print(String(data: rangeOfWorld, encoding: .utf8)!) // "world!"