简体   繁体   中英

Converting CNContact to NSData and vice versa

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.

I realised that I've accidentally archive the CNContact data twice in the code above, and for unarchiving I've only did it once. Changing the code for unarchiving the the one below works:

func session(session: MCSession, didReceiveData data: NSData, fromPeer peerID: MCPeerID) {
    print("Received data: \(data) From Peer: \(peerID)")

    if let contactsData: NSData = NSKeyedUnarchiver.unarchiveObjectWithData(data) as? NSData {
        if let contacts: [CNContact] = NSKeyedUnarchiver.unarchiveObjectWithData(contactsData) as? [CNContact] {
            self.delegate?.didReceiveContacts(contacts, fromPeer: peerID)
        }
    }
}

But however if I only archive the CNContact object once and unarchiving it, it doesn't work. Still have no idea why.

签出CNContactVCardSerialization类

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM