在 iOS 中检索所有联系人电话号码

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17975297/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 00:34:44  来源:igfitidea点击:

Retrieve all contacts phone numbers in iOS

iosobjective-ccontacts

提问by Idan Moshe

So far I saw methods to get multiple phone numbers if I show a picker so user can select people and then get the phone number. What I want is retrieving all contacts' numbers.Is it even possible?

到目前为止,我看到了获取多个电话号码的方法,如果我显示一个选择器,那么用户可以选择人员然后获取电话号码。我想要的是检索所有联系人的号码。甚至有可能吗?

回答by icodebuster

Try this it works for iOS 6 as well as iOS 5.0 or older:

试试这个它适用于iOS 6 以及 iOS 5.0 或更早版本

Sample Project Demo

示例项目演示

First add the following frameworks in Link Binary With Libraries

首先在Link Binary With Libraries中添加以下框架

  • AddressBookUI.framework
  • AddressBook.framework
  • AddressBookUI.framework
  • 地址簿框架

Then Import

然后导入

#import <AddressBook/ABAddressBook.h>
#import <AddressBookUI/AddressBookUI.h>

Then use the following code

然后使用下面的代码

Requesting permission to access address book

请求访问地址簿的权限

ABAddressBookRef addressBook = ABAddressBookCreateWithOptions(NULL, NULL);

__block BOOL accessGranted = NO;

if (&ABAddressBookRequestAccessWithCompletion != NULL) { // We are on iOS 6
    dispatch_semaphore_t semaphore = dispatch_semaphore_create(0);

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

    dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
    dispatch_release(semaphore);
}

else { // We are on iOS 5 or Older
    accessGranted = YES;
    [self getContactsWithAddressBook:addressBook];
}

if (accessGranted) {
    [self getContactsWithAddressBook:addressBook];
}

Retrieving contacts from addressbook

从地址簿中检索联系人

// Get the contacts.
- (void)getContactsWithAddressBook:(ABAddressBookRef )addressBook {

    contactList = [[NSMutableArray alloc] init];
    CFArrayRef allPeople = ABAddressBookCopyArrayOfAllPeople(addressBook);
    CFIndex nPeople = ABAddressBookGetPersonCount(addressBook);

    for (int i=0;i < nPeople;i++) {
        NSMutableDictionary *dOfPerson=[NSMutableDictionary dictionary];

        ABRecordRef ref = CFArrayGetValueAtIndex(allPeople,i);

        //For username and surname
        ABMultiValueRef phones =(__bridge ABMultiValueRef)((__bridge NSString*)ABRecordCopyValue(ref, kABPersonPhoneProperty));

        CFStringRef firstName, lastName;
        firstName = ABRecordCopyValue(ref, kABPersonFirstNameProperty);
        lastName  = ABRecordCopyValue(ref, kABPersonLastNameProperty);
        [dOfPerson setObject:[NSString stringWithFormat:@"%@ %@", firstName, lastName] forKey:@"name"];

        //For Email ids
        ABMutableMultiValueRef eMail  = ABRecordCopyValue(ref, kABPersonEmailProperty);
        if(ABMultiValueGetCount(eMail) > 0) {
            [dOfPerson setObject:(__bridge NSString *)ABMultiValueCopyValueAtIndex(eMail, 0) forKey:@"email"];

        }

        //For Phone number
        NSString* mobileLabel;

        for(CFIndex j = 0; j < ABMultiValueGetCount(phones); j++) {
            mobileLabel = (__bridge NSString*)ABMultiValueCopyLabelAtIndex(phones, j);
            if([mobileLabel isEqualToString:(NSString *)kABPersonPhoneMobileLabel])
            {
                [dOfPerson setObject:(__bridge NSString*)ABMultiValueCopyValueAtIndex(phones, j) forKey:@"phone"];
            }
            else if ([mobileLabel isEqualToString:(NSString*)kABPersonPhoneIPhoneLabel])
            {
                [dOfPerson setObject:(__bridge NSString*)ABMultiValueCopyValueAtIndex(phones, j) forKey:@"phone"];
                break ;
            }

        }
    [contactList addObject:dOfPerson];

    }
NSLog(@"Contacts = %@",contactList);
}

To retrive other information

检索其他信息

// All Personal Information Properties
kABPersonFirstNameProperty;          // First name - kABStringPropertyType
kABPersonLastNameProperty;           // Last name - kABStringPropertyType
kABPersonMiddleNameProperty;         // Middle name - kABStringPropertyType
kABPersonPrefixProperty;             // Prefix ("Sir" "Duke" "General") - kABStringPropertyType
kABPersonSuffixProperty;             // Suffix ("Jr." "Sr." "III") - kABStringPropertyType
kABPersonNicknameProperty;           // Nickname - kABStringPropertyType
kABPersonFirstNamePhoneticProperty;  // First name Phonetic - kABStringPropertyType
kABPersonLastNamePhoneticProperty;   // Last name Phonetic - kABStringPropertyType
kABPersonMiddleNamePhoneticProperty; // Middle name Phonetic - kABStringPropertyType
kABPersonOrganizationProperty;       // Company name - kABStringPropertyType
kABPersonJobTitleProperty;           // Job Title - kABStringPropertyType
kABPersonDepartmentProperty;         // Department name - kABStringPropertyType
kABPersonEmailProperty;              // Email(s) - kABMultiStringPropertyType
kABPersonBirthdayProperty;           // Birthday associated with this person - kABDateTimePropertyType
kABPersonNoteProperty;               // Note - kABStringPropertyType
kABPersonCreationDateProperty;       // Creation Date (when first saved)
kABPersonModificationDateProperty;   // Last saved date

// All Address Information Properties
kABPersonAddressProperty;            // Street address - kABMultiDictionaryPropertyType
kABPersonAddressStreetKey;
kABPersonAddressCityKey;
kABPersonAddressStateKey;
kABPersonAddressZIPKey;
kABPersonAddressCountryKey;
kABPersonAddressCountryCodeKey;

Further Reference Read Apple Docs

进一步参考阅读 Apple 文档

UPDATE:You need to add description about why you need to access the contacts in you Apps-Info.plist

更新:您需要添加有关为什么需要访问您的联系人的说明Apps-Info.plist

Privacy - Contacts Usage Description

Privacy - Contacts Usage Description

OR

或者

<key>NSContactsUsageDescription</key>
<string>Write the reason why your app needs the contact.</string>

For getting the user image.

用于获取用户图像。

UIImage *contactImage;
if(ABPersonHasImageData(ref)){
 contactImage = [UIImage imageWithData:(__bridge NSData *)ABPersonCopyImageData(ref)];
}

NOTE:

笔记:

The AddressBook framework is deprecated in iOS 9and replaced with the new and improved Contacts Framework

AddressBook 框架iOS 9在新的和改进的Contacts Framework 中已被弃用并取而代之

回答by Mannam Brahmam

  • AddressBookUI.framework
  • AddressBook.framework

    These 2 frameworks are deprecated in iOS 9

    ---> Apple introduced

  • Contact Framework
  • ContactUI Framework
  • AddressBookUI.framework
  • 地址簿框架

    这两个框架在 iOS 9 中已弃用

    ---> 苹果介绍

  • 联系框架
  • ContactUI 框架

Hereis uploaded Code using latest frameworks.

是使用最新框架上传的代码。

回答by JeffRegan

Get permission to the address book or notify the user that the need to change the permission in their settings.

获取地址簿的权限或通知用户需要更改其设置中的权限。

CGFloat iOSVersion = [[[UIDevice currentDevice] systemVersion] floatValue];
    if(iOSVersion >= 6.0) {
        // Request authorization to Address Book
        addressBookRef = ABAddressBookCreateWithOptions(NULL, NULL);
        if (ABAddressBookGetAuthorizationStatus() == kABAuthorizationStatusNotDetermined) {
            ABAddressBookRequestAccessWithCompletion(addressBookRef, ^(bool granted, CFErrorRef error) {
                //start importing contacts
                if(addressBookRef) CFRelease(addressBookRef);
            });
        }
        else if (ABAddressBookGetAuthorizationStatus() == kABAuthorizationStatusAuthorized) {
            // The user has previously given access, add the contact
            //start importing contacts
            if(addressBookRef) CFRelease(addressBookRef);
        }
        else {
            // The user has previously denied access
            // Send an alert telling user to change privacy setting in settings app
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Unable to Access" message:@"Grant us access now!" delegate:self cancelButtonTitle:@"Not Now" otherButtonTitles:@"I'll Do It!", nil];
            [alert show];
            if(addressBookRef) CFRelease(addressBookRef);
        }
    } else {
        addressBookRef = ABAddressBookCreate();
        //start importing contacts
        if(addressBookRef) CFRelease(addressBookRef);
    }

Get the records

获取记录

CFArrayRef records = ABAddressBookCopyArrayOfAllPeople(addressBook);
NSArray *contacts = (__bridge NSArray*)records;
CFRelease(records);

for(int i = 0; i < contacts.count; i++) {
    ABRecordRef record = (__bridge ABRecordRef)[contacts objectAtIndex:i];
}

Get the phone number

获取电话号码

    ABMultiValueRef phonesRef    = ABRecordCopyValue(recordRef, kABPersonPhoneProperty);

    if(phonesRef) {
        count = ABMultiValueGetCount(phonesRef);
        for(int ix = 0; ix < count; ix++){
            CFStringRef typeTmp = ABMultiValueCopyLabelAtIndex(phonesRef, ix);
            CFStringRef numberRef = ABMultiValueCopyValueAtIndex(phonesRef, ix);
            CFStringRef typeRef = ABAddressBookCopyLocalizedLabel(typeTmp);

            NSString *phoneNumber = (__bridge NSString *)numberRef;
            NSString *phoneType = (__bridge NSString *)typeRef;


            if(typeTmp) CFRelease(typeTmp);
            if(numberRef) CFRelease(numberRef);
            if(typeRef) CFRelease(typeRef);
        }
        CFRelease(phonesRef);
    }

Keep in mind, some people have 20,000 contacts in their phone. If you plan on doing this, you'll probably have to multithread the process.

请记住,有些人的手机中有 20,000 个联系人。如果您打算这样做,您可能必须对进程进行多线程处理。

回答by Segev

Sure you can. First you'll need to get the user permission for doing so. If you won't the user will have to manually authorize your app from the settings. There's a great example on how to retrieve all phone numbers, names, addresses etc' here.

你当然可以。首先,您需要获得用户许可才能这样做。如果您不这样做,用户将不得不从设置中手动授权您的应用程序。有一个关于如何检索所有的电话号码,姓名,地址等”一个很好的例子在这里