私のアプリでは、新しい連絡先を作成したいと考えています。同じ名前の連絡先が既に存在する場合、新しい連絡先を古い連絡先にリンクしたいと考えています。
CNContact と CNContactStore のリファレンスを調べましたが、連絡先をリンクする方法がわかりません。これは可能ですか?
IOS9 では、同じ人物を表す異なるアカウントの連絡先が自動的にリンクされる場合があります。
これを実現するには、新しく挿入した連絡先の名前が、統合したい連絡先の名前と一致していることを確認する必要があります。
以下にリンクされているドキュメントは、iCloud と Facebook の「John Appleseed」の例を示しています。
以下は、連絡先ストアに既に存在する連絡先と連絡先をマージするコードです。名前、姓などの一意の値が置き換えられ、番号、電子メール、住所などの配列が既存の値に追加されるという参考までに。乾杯!!
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)
}
}