I'm trying to convert CNContact
objects into NSData to be sent to another device over Multipeer Connectivity. Here's my code for sending the contacts data:
func sendContactsToPeer(peerId: MCPeerID, contacts: [CNContact]) {
let contactsData: NSData = NSKeyedArchiver.archivedDataWithRootObject(contacts)
do {
try self.session.sendData(NSKeyedArchiver.archivedDataWithRootObject(contactsData), toPeers: self.session.connectedPeers, withMode: MCSessionSendDataMode.Reliable)
} catch {
print("Unable to send contacts data to \(peerId.displayName)")
}
}
And this is for receiving contacts:
func session(session: MCSession, didReceiveData data: NSData, fromPeer peerID: MCPeerID) {
print("Received data: \(data) From Peer: \(peerID)")
if let contacts: [CNContact] = NSKeyedUnarchiver.unarchiveObjectWithData(data) as? [CNContact] {
self.delegate?.didReceiveContacts(contacts, fromPeer: peerID)
}
}
There is output for the print statement for the NSData
, which indicates that the data is not nil. But when I tried unarchiving the object into an array of CNContacts, it returns nil. Any ideas why?
Note that I've also tried just sending a single CNContact
object instead of an array of them, but the results are the same.