1

How do I read an email address from the address book programmatically using Grant Access? I am aware that this can be achieved with the help of ABPeoplePicker, however I am looking for an approach that does not involve any GUI.

Can anyone help me regarding this matter?

Vatsal Manot
  • 17,695
  • 9
  • 44
  • 80
SJS
  • 2,647
  • 1
  • 17
  • 34

1 Answers1

2
    CFErrorRef error = NULL;
    ABAddressBookRef addressBook = ABAddressBookCreateWithOptions(NULL, &error);

    __block BOOL accessGranted = NO;

    if (ABAddressBookRequestAccessWithCompletion != NULL)
    {
        // we're on iOS 6
        dispatch_semaphore_t sema = dispatch_semaphore_create(0);

        ABAddressBookRequestAccessWithCompletion(addressBook, ^(bool granted, CFErrorRef error)
                                                 {
                                                     accessGranted = granted;
                                                     dispatch_semaphore_signal(sema);
                                                 });

        dispatch_semaphore_wait(sema, DISPATCH_TIME_FOREVER);
    }
    else
    { // we're on iOS 5 or older
        accessGranted = YES;
    }


    if (accessGranted)
    {
        NSArray *allContacts = (__bridge_transfer NSArray*)ABAddressBookCopyArrayOfAllPeople(addressBook);

        NSLog(@"People Count :- %d", (int)[allContacts count]);

        for (int i = 0 ; i < [allContacts count] ; i++)
        {
            ABRecordRef contactPerson = (__bridge ABRecordRef)allContacts[i];

            ABMultiValueRef emails = ABRecordCopyValue(contactPerson, kABPersonEmailProperty);

            NSUInteger j = 0;
            for (j = 0; j < ABMultiValueGetCount(emails); j++)
            {
                NSString *email = (__bridge_transfer NSString *)ABMultiValueCopyValueAtIndex(emails, j);
                if (j == 0)
                    NSLog(@"Person Home Email = %@ ", email);
                else if (j==1)
                    NSLog(@"Person Work Email = %@ ", email);

                emailAddressList = [[EmailAddressList alloc] init];

                emailAddressList.strEmailAddress = email;
                emailAddressList.strEmailAddressType = @"AddressBook";

                [emailAddressList InsertRecordForEmailAddress:emailAddressList];
            }
        }
    }
Mihin
  • 320
  • 1
  • 15
  • this code shows me an error called use of undeclared identifier emailaddresslist what i want to do,any suggestions – Gowtham Sep 14 '17 at 05:12