Благодаря rmaddy и OOPer, я размещаю код здесь.
let commandData = dataWithHexString(hex: "0x18")
let delayTime = DispatchTime.now() + 2
DispatchQueue.main.asyncAfter(deadline: delayTime) {
self.socket.write(commandData, withTimeout: -1.0, tag: 0)
self.socket.readData(withTimeout: -1.0, tag: 0)
}
func dataWithHexString(hex: String) -> Data {
var hex = hex
var data = Data()
while(hex.count > 0) {
let subIndex = hex.index(hex.startIndex, offsetBy: 2)
let c = String(hex[..<subIndex])
hex = String(hex[subIndex...])
var ch: UInt32 = 0
Scanner(string: c).scanHexInt32(&ch)
var char = UInt8(ch)
data.append(&char, count: 1)
}
return data
}