2015-06-19 133 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) 
    } 
} 
相關問題