简体   繁体   中英

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.

Yes, you can do this. It seems suspicious that you would want to do this (why do you need this information?), but it isn't difficult to do.

You can use ABAddressBookCopyArrayOfAllPeople to get an CFArrayRef with all of the people, and then you can query kABPersonEmailProperty of each using ABRecordCopyValue . The code would look something like this (untested):

ABAddressBookRef addressBook = ABAddressBookCreate();
CFArrayRef people = ABAddressBookCopyArrayOfAllPeople(addressBook);
NSMutableArray *allEmails = [[NSMutableArray alloc] initWithCapacity:CFArrayGetCount(people)];
for (CFIndex i = 0; i < CFArrayGetCount(people); i++) {
    ABRecordRef person = CFArrayGetValueAtIndex(people, i);
    ABMultiValueRef emails = ABRecordCopyValue(person, kABPersonEmailProperty);
    for (CFIndex j=0; j < ABMultiValueGetCount(emails); j++) {
        NSString* email = (NSString*)ABMultiValueCopyValueAtIndex(emails, j);
        [allEmails addObject:email];
        [email release];
    }
    CFRelease(emails);
}
CFRelease(addressBook);
CFRelease(people);

(Memory allocation may be a little off; it's been a while since I've developed Cocoa/Core Foundation code.)

But seriously, question why you are doing this. There's a good chance that there's a better solution by just using the Apple-provided APIs to present a contact picker at appropriate times.

ABAddressBookRef allPeople = ABAddressBookCreate();
CFArrayRef allContacts = ABAddressBookCopyArrayOfAllPeople(allPeople);
CFIndex numberOfContacts  = ABAddressBookGetPersonCount(allPeople);

NSLog(@"numberOfContacts------------------------------------%ld",numberOfContacts);


for(int i = 0; i < numberOfContacts; i++){
    NSString* name = @"";
    NSString* phone = @"";
    NSString* email = @"";

    ABRecordRef aPerson = CFArrayGetValueAtIndex(allContacts, i);
    ABMultiValueRef fnameProperty = ABRecordCopyValue(aPerson, kABPersonFirstNameProperty);
    ABMultiValueRef lnameProperty = ABRecordCopyValue(aPerson, kABPersonLastNameProperty);

    ABMultiValueRef phoneProperty = ABRecordCopyValue(aPerson, kABPersonPhoneProperty);\
    ABMultiValueRef emailProperty = ABRecordCopyValue(aPerson, kABPersonEmailProperty);

    NSArray *emailArray = (__bridge NSArray *)ABMultiValueCopyArrayOfAllValues(emailProperty);
    NSArray *phoneArray = (__bridge NSArray *)ABMultiValueCopyArrayOfAllValues(phoneProperty);


    if (fnameProperty != nil) {
        name = [NSString stringWithFormat:@"%@", fnameProperty];
    }
    if (lnameProperty != nil) {
        name = [name stringByAppendingString:[NSString stringWithFormat:@" %@", lnameProperty]];
    }

    if ([phoneArray count] > 0) {
        if ([phoneArray count] > 1) {
            for (int i = 0; i < [phoneArray count]; i++) {
                phone = [phone stringByAppendingString:[NSString stringWithFormat:@"%@\n", [phoneArray objectAtIndex:i]]];
            }
        }else {
            phone = [NSString stringWithFormat:@"%@", [phoneArray objectAtIndex:0]];
        }
    }

    if ([emailArray count] > 0) {
        if ([emailArray count] > 1) {
            for (int i = 0; i < [emailArray count]; i++) {
                email = [email stringByAppendingString:[NSString stringWithFormat:@"%@\n", [emailArray objectAtIndex:i]]];
            }
        }else {
            email = [NSString stringWithFormat:@"%@", [emailArray objectAtIndex:0]];
        }
    }

    NSLog(@"NAME : %@",name);
    NSLog(@"PHONE: %@",phone);
    NSLog(@"EMAIL: %@",email);
    NSLog(@"\n");
}
@import AddressBook;

- (void)addressBookInit {
    if (ABAddressBookGetAuthorizationStatus() == kABAuthorizationStatusDenied || ABAddressBookGetAuthorizationStatus() == kABAuthorizationStatusRestricted){
//        NSLog(@"Denied");
        UIAlertView *cantAddContactAlert = [[UIAlertView alloc] initWithTitle: @"Cannot get contacts" message: @"You must give the app permission to read the contacts first." delegate:nil cancelButtonTitle: @"OK" otherButtonTitles: nil];
        [cantAddContactAlert show];
    } else if (ABAddressBookGetAuthorizationStatus() == kABAuthorizationStatusAuthorized){
//        NSLog(@"Authorized");
        [self getEmails];
    } else {
//        NSLog(@"Not determined");
        ABAddressBookRequestAccessWithCompletion(ABAddressBookCreateWithOptions(NULL, nil), ^(bool granted, CFErrorRef error) {
            dispatch_async(dispatch_get_main_queue(), ^{
                if (!granted){
                    //4
                    UIAlertView *cantAddContactAlert = [[UIAlertView alloc] initWithTitle: @"Cannot get contacts" message: @"You must give the app permission to read the contacts first." delegate:nil cancelButtonTitle: @"OK" otherButtonTitles: nil];
                    [cantAddContactAlert show];
                    return;
                }
//                NSLog(@"Authorized 2");
                [self getEmails];

            });
        });
    }
}

-(NSArray *)getEmails
{
    NSMutableArray *emails = [NSMutableArray array];
    ABAddressBookRef addressBookRef = ABAddressBookCreateWithOptions(NULL, nil);
    NSArray *allContacts = (__bridge NSArray *)ABAddressBookCopyArrayOfAllPeople(addressBookRef);
    for (id record in allContacts)
    {
        ABRecordRef person = (__bridge ABRecordRef)record;
        ABMultiValueRef emailProperty = ABRecordCopyValue(person, kABPersonEmailProperty) ;
        NSArray *personEmails = (__bridge_transfer NSArray *)ABMultiValueCopyArrayOfAllValues(emailProperty);
        [emails addObjectsFromArray:personEmails];
        CFRelease(person);
        CFRelease(emailProperty);
    }
    CFRelease(addressBookRef) ;
    for (NSString *email in emails)
    {
        NSLog(@"%@", email) ;
    }
    return emails;
}

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM