Search code examples
iosswiftvcf-vcardcncontact

How to convert a vCard into a CNContact


I used this piece of code:

 var vcard = NSData()
 let usersContact = CNMutableContact()
 do {
     try vcard = CNContactVCardSerialization.dataWithContacts([usersContact])
 } catch {
     print("Error \(error)")
 }

to convert a CNMutableContact into a vCard which seems to be working. When I try to convert the vCard back however using this (in another viewController using a segue to send the data which I'm pretty confident is working):

var vCardSFR = NSData()
var usersContact = CNContact()
....more code....
do {
    try usersContact = CNContactVCardSerialization.contactsWithData(vCardSFR)


} catch {
    print("Error \(error)")
}

but I get an error saying it cannot cannot assign value of type [AnyObject] to type CNContact. So then I try initializing CNContact this way:

var usersContact = [CNContact()]

but then I get an error saying cannot assign value of type [AnyObject] to type [CNContact]. I'm think there's a very simple solution to this however I don't know what it might be. I've been using this to get my code for the vCards: https://developer.apple.com/library/prerelease/mac/documentation/Contacts/Reference/CNContactVCardSerialization_Class/index.html#//apple_ref/occ/clm/CNContactVCardSerialization/contactsWithData:error:

Any help would be very much appreciated!


Solution

  • I used

    var usersContact = []
    do {
        try usersContact = CNContactVCardSerialization.contactsWithData(vCardSFR)
    
    
    } catch {
        print("Error \(error)")
    }
    

    and then

    var contact = usersContact[0] as! CNContact