2015-06-19 94 views
3

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

我已经看过CNContact和CNContactStore的引用,并没有看到任何链接联系人的方式。这是可能的,如果是的话,如何?

+0

您是否找到合并两个联系人而不是创建新的'CNMutableContact'并手动合并忽略重复项的属性的方法?如果你能够合并两个联系人,你能告诉如何? – Adeel

+0

@Adeel我还没有找到解决方案,但我还没有找过一段时间。 – erdekhayser

回答

0

下面是store.Just等给出的名字姓一个供参考的独特价值将被替换和代码合并与接触的已经存在接触的接触区域,如号码,电子邮件,地址将附加现有的值。干杯!!

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) 
    } 
} 
相关问题