如何使用Grant Access以编程方式从地址簿中获取电子邮件地址? (目标C)

时间:2014-05-02 08:34:15

标签: ios objective-c addressbook abpeoplepickerview

如何使用授权访问以编程方式从地址簿中读取电子邮件地址?我知道这可以在ABPeoplePicker的帮助下实现,但我正在寻找一种不涉及任何GUI的方法。

有人可以帮我解决这个问题吗?

1 个答案:

答案 0 :(得分: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];
            }
        }
    }