I'm trying to get my head around Swift and have promised myself my next app will be a SwiftUI appp... I am trying hard to update my thinking away from C style pointers and so on, but here's something thats got me stumped so far.
My app will communicate with an embedded network device. The device sends me packets of data with a well-defined header followed by an optional payload of data bytes.
In C (on the device) the header is defined like this:
typedef struct _MSG_TYPE
{
uint16_t sig;
uint16_t len; // Total length of message, include header and playload;
uint16_t type;
uint32_t data; // 32 Bits of data.
} MSG_t;
And my app will respond with messages using the same type of header. Since I'm trying to do this in Swift I somehow need to get my C-type structs in-and-out of Swift style Data types. Here's my receive function:
private func receive_data() {
nwConnection.receive(minimumIncompleteLength: 1, maximumLength: 65536) { (data, _, isComplete, error) in
if let data = data, !data.isEmpty {
print("connection did receive, data: \(data as NSData) ")
if let msgCallback = self.messageDeliveryCallback {
msgCallback(data)
}
}
if isComplete {
self.connectionDidEnd()
} else if let error = error {
self.connectionDidFail(error: error)
} else {
self.receive_data()
}
}
}
And the callback which it calls looks like this:
func messageDelivery(message: Data?)
{
if let data = message, !data.isEmpty {
}
}
So my questions is. In the callback - how do I get the data from the Data type into one of my MSG_t structs? Or is there a better way to extract the equivalent bytes?
And for sending message back to the client, how do I get one of my MSG_t structs into a swift Data type?
I looked at using something like:
var getInfoMsg = MSG_t(sig: UInt16(MSG_SIG), len: UInt16(MemoryLayout<MSG_t>.size), type: UInt16(MSG_TYPE_GET_INFO), data: 0)
var newData = Data(bytes: UnsafeRawPointer(getInfoMsg), count: Int(getInfoMsg.len))
But that doesn't seem right and give an error:
No exact matches in call to initializer
Hah. Sorry if this is a ****** question - like I say, trying to learn swift, but I'm old and slow!!
So how do I convert to/from my MSG_t to Data in swift?