I'm developing an app where the user can create some records relevant to a CNContact. I use CoreData and CloudKit to save those data.When saving data, I have 1 attribute to store the CNContact.identifier in my CoreData Entity. Then I find the Contact details using that identifier. This method works perfectly fine on a single device.
Since this app supports iCloud Sync, the users can access the same data from their other devices. Even though the other device has all the same Contacts, the app couldn't find the relevant CNContact from the CNContact.identifier saved in the CoreData attribute. Turns out CNContact.identifier is not the same for a single contact on different device.
So What I want to know is... how can I detect the same Contact in multiple devices? What data should I store in CoreData in order to successfully achieve this?
I have an app that also has the same functionality where the user can select a contact and the app data is synced across their devices via CloudKit.
In my app I store the contact's identifier and what I call a "composite name". I calculate the "composite name" using the first available value from the following list:
When looking up the corresponding contact on another device, I of course begin by looking for a contact with the same identifier. If that's not found, I then search the contacts using the "composite name".
This begins by using CNContact predicateForContacts(matchingName:)
(passing in the "composite name") with CNContactStore unifiedContacts(matching:keysToFetch:)
. If that doesn't give any results then I enumerate all contacts and find the first contact whose name, company name, phone number, or email address matches the "composite name".
This certainly doesn't guarantee the correct contact is always selected. Depending on the user's contacts, this could result in the wrong contact being selected. But overall, it seems to work well enough. Adjust as needed based on the needs of your app.