如何获取新创建联系人的contact.identifier

时间:2018-09-27 12:02:18

标签: swift contacts cncontactstore

func createContact() {

        let store = CNContactStore()
        let contactToAdd = CNMutableContact()
        contactToAdd.phoneticGivenName = "Harshad"
        contactToAdd.phoneticMiddleName = "I"
        contactToAdd.phoneticFamilyName = "Pipaliya"

        contactToAdd.emailAddresses.append(CNLabeledValue(label: CNLabelPhoneNumberMain, value: "test@icloud.com"))

        let saveRequest = CNSaveRequest()
        saveRequest.add(contactToAdd, toContainerWithIdentifier: nil)
        do {
            try store.execute(saveRequest)   // Here I need to get identifier of created new contact
        }
        catch {
            print(error)
        }
    }

我试图通过应用创建标识符,但是我做不到。

预先感谢

1 个答案:

答案 0 :(得分:0)

这是在创建联系人时获取联系人ID的方法

func createContact() {

        let store = CNContactStore()
        let contactToAdd = CNMutableContact()
        contactToAdd.phoneticGivenName = "Harshad"
        contactToAdd.phoneticMiddleName = "I"
        contactToAdd.phoneticFamilyName = "Pipaliya"

        contactToAdd.emailAddresses.append(CNLabeledValue(label: CNLabelPhoneNumberMain, value: "test@icloud.com"))

        let saveRequest = CNSaveRequest()
        saveRequest.add(contactToAdd, toContainerWithIdentifier: nil)
        do {
            try store.execute(saveRequest)
            if contactToAdd.isKeyAvailable(CNContactIdentifierKey) {
                print(contactToAdd.identifier) // this is the wat to get identifier of contact when creating new
            }
        }
        catch {
            print(error)
        }
    }