以编程方式链接CNContacts

时间:2015-06-19 17:33:03

标签: ios contacts ios9

在我的应用中,我想创建一个新联系人。如果已存在具有相同名称的联系人,我想将新联系人链接到旧联系人。

我查看了CNContact和CNContactStore参考,并且没有看到任何链接联系人的方法。这是可能的,如果是的话,怎么样?

3 个答案:

答案 0 :(得分:1)

在IOS9中,代表同一个人的不同帐户中的联系人可能会自动链接在一起。

要实现此目的,您应确保新插入的联系人的姓名与您想要统一的联系人姓名一致。

下面链接的文档给出了" John Appleseed"在iCloud和Facebook上。

https://developer.apple.com/library/watchos/documentation/Contacts/Reference/Contacts_Framework/index.html

答案 1 :(得分:0)

以下是将联系人与联系人商店中已存在的联系人合并的代码。只有一个FYI,将替换给定姓名系列名称等唯一值,并且数字,电子邮件,地址等数组将附加现有值。干杯!!

func contactPicker(_ picker: CNContactPickerViewController, didSelect contact: CNContact) {
    picker.dismiss(animated: true, completion: nil)
    let identifier = contact.identifier
    updateContact(contactIdentifier: identifier)
}

func updateContact(contactIdentifier: String){

    let keysToFetch = [CNContactViewController.descriptorForRequiredKeys()]
    let contactStore = CNContactStore()
    do {
        let contactToUpdate =  try contactStore.unifiedContact(withIdentifier: contactIdentifier, keysToFetch: keysToFetch).mutableCopy() as! CNMutableContact
        if contactToUpdate.familyName.trimmingCharacters(in: .whitespacesAndNewlines) == "" {
            contactToUpdate.familyName = "your value"
        }
        if contactToUpdate.givenName.trimmingCharacters(in: .whitespacesAndNewlines) == "" {
            contactToUpdate.givenName = "your value"
        }
        if contactToUpdate.organizationName.trimmingCharacters(in: .whitespacesAndNewlines) == "" {
            contactToUpdate.organizationName = "your value"
        }
        if contactToUpdate.jobTitle.trimmingCharacters(in: .whitespacesAndNewlines) == "" {
            contactToUpdate.jobTitle = "your value"
        }
  // here the contact used below is the one that you want to merge with 
     an existing one.

        for i in contact.phoneNumbers {
            contactToUpdate.phoneNumbers.append(i)
        }
        for i in contact.emailAddresses {
            contactToUpdate.emailAddresses.append(i)
        }
        for i in contact.postalAddresses {
            contactToUpdate.postalAddresses.append(i)
        }
        let contactsViewController = CNContactViewController(forNewContact: contactToUpdate)
        contactsViewController.delegate = self
        contactsViewController.title = "Edit contact"
        contactsViewController.contactStore = contactStore
        let nav = UINavigationController(rootViewController: contactsViewController)
        DispatchQueue.main.async {
            self.present(nav, animated: true, completion: nil)
        }

    }
    catch {
        print(error.localizedDescription)
    }
}

答案 2 :(得分:0)

我不确定这一点,但我怀疑 iOS 只能跨不同来源合并。如果您在同一个地址簿中创建两个联系人,它们将不会合并。

联系人库中对这个区域的支持很少。您可以使用 CNContact.isUnifiedWithContact(withIdentifier:) 检测一个联系人是否已统一并链接到另一个特定联系人,您可以决定是否要返回统一联系人。

相关问题