如何在CNContactVCardSerialization中使用方法dataWithContacts?

时间:2015-09-30 03:50:37

标签: ios swift contacts vcard

我正在尝试使用联系人的vCard表示获取NSData对象。我的代码:

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)")
      } 

但是,我得到错误:

  

将联系人写入vCard(数据)的异常:获取联系人时未请求属性。错误NilError。

我理解访问联系人的错误,但如何解决?

1 个答案:

答案 0 :(得分:4)

我找到了解决方案并且可行:

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)")
}

但是,我从vCard数据中返回联系人:

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

字段联系人imageData没有。虽然不是零。