在我的应用程序中,我想创建一个新联系人。如果已存在同名联系人,我想将新联系人链接到旧联系人。
我查看了 CNContact 和 CNContactStore 参考资料,但没有看到任何链接联系人的方法。这可能吗?如果可以,怎么做?
在 IOS9 中,代表同一个人的不同帐户中的联系人可能会自动链接在一起。
为此,您应该确保新插入的联系人的姓名与您要与之统一的联系人的姓名相匹配。
下面链接的文档给出了 iCloud 和 Facebook 上“John Appleseed”的示例。
我不确定这一点,但我怀疑 iOS 只合并不同的来源。如果您在同一个通讯录中创建两个联系人,它们将不会被合并。
联系人库中对此区域的支持很少。您可以使用 CNContact.isUnifiedWithContact(withIdentifier:) 检测联系人是否统一并链接到另一个特定联系人,并且您可以决定是否要返回统一联系人。
以下是将联系人与联系人存储中已存在的联系人合并的代码。仅供参考,将替换给定姓名等唯一值,并将数字、电子邮件、地址等数组附加到现有值。干杯!!
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)
}
}