Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get all E-Mail addresses from contacts (iOS)

I know it is possible to pull up a contact and see information based on one contact. But is there any way to get all the emails from the contacts you have entered email addresses for and then store that in a NSArray? This is my first time working with contacts so I don't know much about it.

like image 758
SimplyKiwi Avatar asked Jul 28 '11 20:07

SimplyKiwi


1 Answers

for iOS 9+, use Contacts framework, Objective C

-(NSArray*)getAllContacts{
__block NSMutableArray *allContacts = nil;
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, CNContactEmailAddressesKey, 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 {
            allContacts = [NSMutableArray array];
            for (CNContact *contact in cnContacts) {
                // copy data to my custom Contacts class.
                // create custom class Contacts with firstName,lastName,image and emailAddress
                for (CNLabeledValue<NSString*> *email in contact.emailAddresses) {
                    Contact *newContact = [[Contact alloc] init];
                    newContact.firstName = contact.givenName;
                    newContact.lastName = contact.familyName;
                    UIImage *image = [UIImage imageWithData:contact.imageData];
                    newContact.image = image;
                    newContact.emailAddress = email.value;
                    [allContacts addObject:newContact];
                }
            }
        }
    }
}];
return allContacts;}
like image 68
Shrey Avatar answered Oct 13 '22 01:10

Shrey