0

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.

1 Answer 1

1

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/.

Sign up to request clarification or add additional context in comments.

2 Comments

thanks @Rob. As I have only been learning Swift, I just presumed the best path was to not use the "NS"-prefixed classes and protocols, as remnants from Objective-C and NextStep. Is this incorrect? Won't they be phased out? Or should I still be assessing each use case and consider the variations between them, i.e. Codable sounds simpler / lightweight, but perhaps misses some capabilities from NSCoding?
That's incorrect. There are many things that Swift stdlib is lacking that Foundation ("NS") can do. Codable isn't simpler or lighter weight. It solves a different problem. That problem is often convenient ("turn into JSON" mostly, but also "turn into plist"). But if your problem is "send full object over a network," then Codable can't do that.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.