Programmatically Associate CNContacts

In my application, I want to create a new contact. If a contact with the same name already exists, I want to associate a new contact with an old one.

I have looked at the CNContact and CNContactStore links and see no way to link the contacts. Is this possible, and if so, how?

+3
source share
2 answers

In IOS9 contacts in different accounts that represent the same person, they can be automatically connected to each other.

To achieve this, you must make sure that the name of your newly inserted contact matches the name of the contact you would like to associate with.

"John Appleseed" iCloud Facebook.

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

+1

. 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)
    }
}
0

Source: https://habr.com/ru/post/1664430/


All Articles