iosobjective-ciphonecncontactcncontactstore

How to get RecordID from CNContactStore ios


This is my code to get the device's Contacts and save to MutableArray.

But I need to get the recordID for all contacts individually and save into the same Array for further use. (For example, to delete Contacts using recordId).

Please help me, I'm stuck for 4 days on that.

[contactStore enumerateContactsWithFetchRequest:request error:nil usingBlock:^(CNContact* __nonnull contact, BOOL* __nonnull stop){
           if( contact.phoneNumbers)
                phoneNumber = [[[contact.phoneNumbers firstObject] value]];
           if( contact.emailAddresses)
                emailAddress = [[contact.emailAddresses firstObject] value];
           contactValue=[[NSMutableDictionary alloc] init];               
                [contactValue setValue:phoneNumber ?:@"" forKey:@"phoneNumber"];
                [contactValue setValue:emailAddress ?:@"" forKey:@"emailAddress"];
                [contactValue setObject:contact.identifier forKey:@"phoneIdentifier"];
                [contactValue setObject:contact.givenName ?:@"" forKey:@"firstName"];
                [contactValue setObject:contact.familyName ?:@"" forKey:@"lastName"];

           [_totalContact addObject:contactValue];
      }]

Solution

  • From your question statement what I understand is that you want to delete a contact from the contact book based on the identifier of that contact. When you have the identifier then this is all you need to do:

    - (void)deleteContactWithIdentifier:(NSString *)identifier {
    
        NSArray *keys = @[CNContactGivenNameKey,
                          CNContactPhoneNumbersKey,
                          CNContactEmailAddressesKey,
                          CNContactIdentifierKey];
        CNMutableContact *contact = [[store unifiedContactWithIdentifier:identifier keysToFetch:keys error:nil] mutableCopy];
        NSError *error;
        CNSaveRequest *saveRequest = [[CNSaveRequest alloc] init];
        [saveRequest deleteContact:contact];
        [store executeSaveRequest:saveRequest error:&error];
    }