0

I have a function like this in android project

override fun send(data: ByteArray?) {

    if (data == null || data.isEmpty()) {
      warn { "Empty Request" }
      return
    }

    webSocket?.send(ByteString.of(ByteBuffer.wrap(data)))
  }

I have written the equivalent code in swift as

func send(data: [UInt8]?) {
        if(data == nil || data?.count == 0) { return }
        var dataString = String(data: Data(bytes: data!, count: data!.count), encoding : String.Encoding.utf8)!
        if(self.webSocket != nil) {
            self.webSocket!.send(text: dataString)
        }
    }

But I found that my code in swift is breaking when any element of UInt8 array is above 127 ie. anything between 128-255. So how will I achieve the equivalent of Java code in swift.

1 Answers1

-2

I tried using NSString and was able to get a valid string with array elements >127.

Here is my playground code.

import UIKit

var data = [UInt8]()

data.append(0)
data.append(120)
data.append(254)

print(UInt8.max)

print(data)

var dataString =  NSString(bytes: data, length: data.count, encoding: 0)
print(dataString as Any)

Not sure if this is a correct encoded string and will probably cause issues at the other end.

humblePilgrim
  • 1,818
  • 4
  • 25
  • 47