How to use method dataWithContacts in CNContactVCardSerialization?

I am trying get NSData object with the vCard representation of the contact. My code:

let contactStore = CNContactStore()
let fetchRequest = CNContactFetchRequest(keysToFetch: [CNContactGivenNameKey, CNContactFamilyNameKey])

var contacts = [CNContact]()
var vcard = NSData()

    do{
            try contactStore.enumerateContactsWithFetchRequest(fetchRequest) { (contact, status) -> Void in
            self.fetchRequest.unifyResults = true
            self.contacts.append(contact)}

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


    do {
           try vcard = CNContactVCardSerialization.dataWithContacts(contacts)
    } catch {
          print("Error \(error)")
      } 

But, i get error:

  • Xcode 8 can't open Model.xcdatamodeld
  • Add spheres at these points of the special SCNBox?
  • UITableViewHeaderFooterView subclass with auto layout and section reloading won't work well together
  • Test app on iPhone without paying $99 to Apple
  • How to add a touch event to a UIView?
  • PresentViewController from custom TableCell in xib
  • Exception writing contacts to vCard (data): A property was not requested when contact was fetched. Error NilError.

    I understand that the error in the access to contacts, but how to fix it?

    Solutions Collect From Internet About “How to use method dataWithContacts in CNContactVCardSerialization?”

    I found the solution and it work:

    let contactStore = CNContactStore()
    var contacts = [CNContact]()
    var vcardFromContacts = NSData()
    
    let fetchRequest = CNContactFetchRequest(keysToFetch:[CNContactVCardSerialization.descriptorForRequiredKeys()])
    
    do{
        try contactStore.enumerateContactsWithFetchRequest(fetchRequest, usingBlock: {
        contact, cursor in
        self.contacts.append(contact)})
    } catch {
        print("Get contacts \(error)")
    }
    
    // Returns the vCard representation of the specified contacts
    
    do {
        try vcardFromContacts = CNContactVCardSerialization.dataWithContacts(contacts)
    } catch {
        print("vcardFromContacts \(error)")
    }
    

    But, whet i returns the contacts from the vCard data:

    do {
        try contactsFromVcard = CNContactVCardSerialization.contactsWithData(vcardFromContacts)
    } catch {
        print("contactsFromVcard \(error)")
    }
    

    field contact imageData has nil. Though it not nil.