How to get contact.identifier of new created contact

221 views Asked by At
func createContact() {

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

        contactToAdd.emailAddresses.append(CNLabeledValue(label: CNLabelPhoneNumberMain, value: "[email protected]"))

        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)
        }
    }

I Tried to create an identifier from an app but I can't able to do.

Thanks In advance

1

There are 1 answers

0
Harsh Pipaliya On

This is the way to get contact id when creating contact

func createContact() {

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

        contactToAdd.emailAddresses.append(CNLabeledValue(label: CNLabelPhoneNumberMain, value: "[email protected]"))

        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)
        }
    }