Multipeer Connectivity, converting data types

There are (few) online examples of people using MultipeerConnectivity to send String data types between devices, such as

There are online examples / tutorials about how to get data from URLRequests, with the Data type in the completion handler.

How do I convert any data type into a Swift “Data” type / class? And can I then append this with:

mcSession.send(data: Data, toPeers: [MCPeerID], with: MCSessionSendDataMode)

An example would be to send a PHAssetCollection object between Apple devices, using PhotoKit (import photos) framework. It would seem I need to change the data type from class PHAssetCollection to Data. But I don’t know where to start…

hi @jingo_man,
Data is an array of bytes. You can convert most of the objects into data by serializing it.

In this case, look deeper into PHAsset, you get Image represetnation that you can convert or get the Data for.


Thanks @jayantvarma

I was hoping to do some processing / checking values of the PHAssetCollection “array” before getting bogged down in the contained images as PHAsset’s within the collection.

I hope that makes sense.

In my limited knowledge and capability, the other option seems to be to loop or enumerate the PHAssetCollection object into different an array(s) containing the data I am interested in.

@jayantvarma Can you provide pointers to serialize objects into Data objects? Specifically I’d like to understand how a custom class, made up with properties of standard data types can be converted to Data, then sent via MC framework…

Hi @jingo_man,
I will try to create some sample code to illustrate (if I get some time) the point is very simple, you can use NSArchiver, JSON or a dictionary to save your object data and create a Data from it, now when you send it across, you need to use the same technique to recreate your object, like encode and decode.


This topic was automatically closed after 166 days. New replies are no longer allowed.