iosabaddressbookabpeoplepickerviewaddressbookui

How to fetch contact id in your iOS app?


I am new to iOS and I have fetched contacts in my app, but how to fetch the contact id... suppose if there are two numbers saved with the same name, so how to fetch that particular contact name's id?


Solution

  • You may try like this : import framework

    #import <Contacts/Contacts.h>
    

    Code

    - (void) getContacts {
        CNContactStore *store = [[CNContactStore alloc] init];
        [store requestAccessForEntityType:CNEntityTypeContacts completionHandler:^(BOOL granted, NSError * _Nullable error) {
            if (granted == YES) {
                //keys with fetching properties
                NSArray *keys = @[CNContactFamilyNameKey, CNContactGivenNameKey, CNContactPhoneNumbersKey, CNContactImageDataKey];
                NSString *containerId = store.defaultContainerIdentifier;
                NSPredicate *predicate = [CNContact predicateForContactsInContainerWithIdentifier:containerId];
                NSError *error;
                NSArray *cnContacts = [store unifiedContactsMatchingPredicate:predicate keysToFetch:keys error:&error];
                if (error) {
                    NSLog(@"error fetching contacts %@", error);
                } else {
                    for (CNContact *contact in cnContacts) {
                        //store all the contacts as per your requirement
                        NSLog(@"Id %@",contact.identifier);//the contact id which you want
                        NSLog(@"Name %@",contact.givenName);
                    }
                }
            }        
        }];
    }