Reputation: 529
I am sending data between devices, that is an JSON encoded custom class I have created that conforms to Codable.
let encoder = JSONEncoder()
do {
let data = try encoder.encode(assets)
try appDelegate.mpcManager.session.send(data, toPeers: appDelegate.mpcManager.connectedPeers, with: MCSessionSendDataMode.reliable)
} catch {
print("sendAssets Error: \(error)")
}
When the receiving device's MCSession didRecieve delegate method is executed, how do I detect the decoded type within / behind the Data object that was sent to the function?
session(_ session: MCSession, didReceive data: Data, fromPeer peerID: MCPeerID)
The data
instance does not have the ".dynamictype" property that other threads provide as a way to detect types.
Perhaps my app architecture is improper, but I am trying out different things with MultipeerConnectivity and thought I might be able to send any type of custom Codable data type, and there would be a way to handle the decoding and conditional testing afterwards.
Upvotes: 0
Views: 181
Reputation: 299505
JSON does not encode types. It just encodes data. It's up to you to decide how to map that data to types in your system. If you need to tell the other side what the type is, you'll need to encode that in the JSON.
If you're only working with Cocoa devices (iOS/macOS), you may want to use NSSecureCoding
and NSKeyedArchiver
rather than JSON. This format does send type information, and is designed for sending full objects (rather than just data) between programs. For an example project, see https://www.objc.io/issues/8-quadcopter/the-quadcopter-client-app/.
Upvotes: 1