2

I am a beginner developer, so I hope I can explain my problem correctly.

I get some data from a Bluetooth device, and then I use this code to encode the data and send them to an endpoint

let encoder = JSONEncoder()
encoder.dataEncodingStrategy = .deferredToData
let encodedData = try encoder.encode(data)
let finalArray = encodedData.compactMap { $0 }

and then ...

try JSONEncoder().encode(finalArray)

The final structure that send to server is not something that we expected.

so I used this extension to convert the data to hex string

extension Data {
    struct HexEncodingOptions: OptionSet {
        let rawValue: Int
        static let upperCase = HexEncodingOptions(rawValue: 1 << 0)
    }

    func hexEncodedString(options: HexEncodingOptions = []) -> String {
        let format = options.contains(.upperCase) ? "%02hhX" : "%02hhx"
        return map { String(format: format, $0) }.joined()
    }
}

The outcome is exactly looks that I expected, now I need to send the data to the endpoint, but I can't send the array of string to the sever, my question is how I can send the data as data with this new hex string format?

thank you so much

Leo Dabus
  • 229,809
  • 59
  • 489
  • 571
Robert kont
  • 165
  • 1
  • 8

1 Answers1

0

You can avoid converting your data to string and back to data manually encoding your bytes. Try like this:

extension RangeReplaceableCollection where Element == UInt8 {
    var hexaEncoded: Self {
        reduce(.init()) {
            let a = $1 / 16
            let b = $1 % 16
            return $0 + [a + (a < 10 ? 48 : 87),
                         b + (b < 10 ? 48 : 87)]
        }
    }
}

extension Sequence where Element == UInt8 {
    var string: String? { String(bytes: self, encoding: .utf8) }
}

let data = Data([0,127,255]) // "007fff"
let hexaEncodedData = data.hexaEncoded // 6 bytes [48, 48, 55, 102, 102, 102]
let hexaEncodedString = hexaEncodedData.string  // "007fff"
Leo Dabus
  • 229,809
  • 59
  • 489
  • 571