I have this Int
number that I have to transmit over the network.
I am using this class extension.
extension Data {
init<T>(from value: T) {
self = Swift.withUnsafeBytes(of: value) { Data($0) }
}
func to<T>(type: T.Type) -> T? where T: ExpressibleByIntegerLiteral {
var value: T = 0
guard count >= MemoryLayout.size(ofValue: value) else { return nil }
_ = Swift.withUnsafeMutableBytes(of: &value, { copyBytes(to: $0)} )
return value
}
}
I encode and send it using this from an iOS device:
let number = button.number
let buttonNumberData = Data(from:number)
do {
try session.send(buttonNumberData, toPeers: session.connectedPeers, with: .reliable)
} catch let error as NSError {
}
}
if I do a po buttonNumberData
at this time, I get:
▿ 4 bytes
- count : 4
▿ pointer : 0x002e9940
- pointerValue : 3053888
▿ bytes : 4 elements
- 0 : 1
- 1 : 0
- 2 : 0
- 3 : 0
If I decode the data using this,
let buttonNumber = buttonNumberData.to(type: Int.self)
I have a valid number.
then, this Data
is transmitted and reaches a macOS computer and is decoded using the same command:
let buttonNumber = buttonNumberData.to(type: Int.self)
The problem is that buttonNumber is always nil
, but if I do a po buttonNumberData
at this point, I have this:
▿ 4 bytes
- count : 4
▿ pointer : 0x00007ffeefbfd428
- pointerValue : 140732920747048
▿ bytes : 4 elements
- 0 : 1
- 1 : 0
- 2 : 0
- 3 : 0
what appears to be valid data.
It appears some problem on the Data
extension class related to how macOS works.
Any ideas?