关于通讯录

iOS9 以下时:

一:选择一个联系人的电话号码

这里不需要先获取所有的联系人自己做联系人列表,直接使用系统自带的AddressBookUI/ABPeoplePickerNavigationController.h就好。

首先需要引入如下三个文件

#import <AddressBookUI/ABPeoplePickerNavigationController.h>

#import <AddressBook/ABPerson.h>

#import <AddressBookUI/ABPersonViewController.h>

然后初始化ABPeoplePickerNavigationController。

ABPeoplePickerNavigationController *nav = [[ABPeoplePickerNavigationController alloc] init];
nav.peoplePickerDelegate = self;
if(IOS8_OR_LATER){
    nav.predicateForSelectionOfPerson = [NSPredicate predicateWithValue:false];
}
[self presentViewController:nav animated:YES completion:nil];

在iOS8之后,需要添加nav.predicateForSelectionOfPerson = [NSPredicate predicateWithValue:false];这一段代码,否则选择联系人之后会直接dismiss,不能进入详情选择电话。

最后设置代理

//取消选择
- (void)peoplePickerNavigationControllerDidCancel:(ABPeoplePickerNavigationController *)peoplePicker
{
    [peoplePicker dismissViewControllerAnimated:YES completion:nil];
}

iOS8下

- (void)peoplePickerNavigationController:(ABPeoplePickerNavigationController *)peoplePicker didSelectPerson:(ABRecordRef)person property:(ABPropertyID)property identifier:(ABMultiValueIdentifier)identifier {
    ABMultiValueRef phone = ABRecordCopyValue(person, kABPersonPhoneProperty);
    long index = ABMultiValueGetIndexForIdentifier(phone,identifier);
    NSString *phoneNO = (__bridge NSString *)ABMultiValueCopyValueAtIndex(phone, index);

    if ([phoneNO hasPrefix:@"+"]) {
        phoneNO = [phoneNO substringFromIndex:3];
    }

    phoneNO = [phoneNO stringByReplacingOccurrencesOfString:@"-" withString:@""];
    NSLog(@"%@", phoneNO);
    if (phone && [ZXValidateHelper checkTel:phoneNO]) {
        phoneNum = phoneNO;
        [self.tableView reloadData];
        [peoplePicker dismissViewControllerAnimated:YES completion:nil];
        return;
    }
}

- (void)peoplePickerNavigationController:(ABPeoplePickerNavigationController*)peoplePicker didSelectPerson:(ABRecordRef)person
{
    ABPersonViewController *personViewController = [[ABPersonViewController alloc] init];
    personViewController.displayedPerson = person;
    [peoplePicker pushViewController:personViewController animated:YES];
}

iOS7下

- (BOOL)peoplePickerNavigationController:(ABPeoplePickerNavigationController *)peoplePicker shouldContinueAfterSelectingPerson:(ABRecordRef)person
{
    return YES;
}

- (BOOL)peoplePickerNavigationController:(ABPeoplePickerNavigationController *)peoplePicker shouldContinueAfterSelectingPerson:(ABRecordRef)person property:(ABPropertyID)property identifier:(ABMultiValueIdentifier)identifier
{
    ABMultiValueRef phone = ABRecordCopyValue(person, kABPersonPhoneProperty);
    long index = ABMultiValueGetIndexForIdentifier(phone,identifier);
    NSString *phoneNO = (__bridge NSString *)ABMultiValueCopyValueAtIndex(phone, index);
    if ([phoneNO hasPrefix:@"+"]) {
        phoneNO = [phoneNO substringFromIndex:3];
    }

    phoneNO = [phoneNO stringByReplacingOccurrencesOfString:@"-" withString:@""];
    NSLog(@"%@", phoneNO);
    if (phone && [ZXValidateHelper checkTel:phoneNO]) {
        phoneNum = phoneNO;
        [self.tableView reloadData];
        [peoplePicker dismissViewControllerAnimated:YES completion:nil];
        return NO;
    }
    return YES;
}

二:获取通讯录

这里需要读取通讯录数据。
首先引入头文件
#import <AddressBook/AddressBook.h>

其次根据权限生成通讯录

- (void)loadPerson
{
    ABAddressBookRef addressBookRef = ABAddressBookCreateWithOptions(NULL, NULL);

    if (ABAddressBookGetAuthorizationStatus() == kABAuthorizationStatusNotDetermined) {
        ABAddressBookRequestAccessWithCompletion(addressBookRef, ^(bool granted, CFErrorRef error){

            CFErrorRef *error1 = NULL;
            ABAddressBookRef addressBook = ABAddressBookCreateWithOptions(NULL, error1);
            [self copyAddressBook:addressBook];
        });
    }
    else if (ABAddressBookGetAuthorizationStatus() == kABAuthorizationStatusAuthorized){

        CFErrorRef *error = NULL;
        ABAddressBookRef addressBook = ABAddressBookCreateWithOptions(NULL, error);
        [self copyAddressBook:addressBook];
    }
    else {
        dispatch_async(dispatch_get_main_queue(), ^{
            // 更新界面
            [hud turnToError:@"没有获取通讯录权限"];
        });
    }
}

然后循环获取每个联系人的信息,建议自己建个model存起来。

- (void)copyAddressBook:(ABAddressBookRef)addressBook

{

CFIndex numberOfPeople = ABAddressBookGetPersonCount(addressBook);

CFArrayRef people = ABAddressBookCopyArrayOfAllPeople(addressBook);

for ( int i = 0; i < numberOfPeople; i++){

ABRecordRef person = CFArrayGetValueAtIndex(people, i);

NSString *firstName = (__bridge NSString *)(ABRecordCopyValue(person, kABPersonFirstNameProperty));

NSString *lastName = (__bridge NSString *)(ABRecordCopyValue(person, kABPersonLastNameProperty));

//读取middlename

NSString *middlename = (__bridge NSString*)ABRecordCopyValue(person, kABPersonMiddleNameProperty);

//读取prefix前缀

NSString *prefix = (__bridge NSString*)ABRecordCopyValue(person, kABPersonPrefixProperty);

//读取suffix后缀

NSString *suffix = (__bridge NSString*)ABRecordCopyValue(person, kABPersonSuffixProperty);

//读取nickname呢称

NSString *nickname = (__bridge NSString*)ABRecordCopyValue(person, kABPersonNicknameProperty);

//读取firstname拼音音标

NSString *firstnamePhonetic = (__bridge NSString*)ABRecordCopyValue(person, kABPersonFirstNamePhoneticProperty);

//读取lastname拼音音标

NSString *lastnamePhonetic = (__bridge NSString*)ABRecordCopyValue(person, kABPersonLastNamePhoneticProperty);

//读取middlename拼音音标

NSString *middlenamePhonetic = (__bridge NSString*)ABRecordCopyValue(person, kABPersonMiddleNamePhoneticProperty);

//读取organization公司

NSString *organization = (__bridge NSString*)ABRecordCopyValue(person, kABPersonOrganizationProperty);

//读取jobtitle工作

NSString *jobtitle = (__bridge NSString*)ABRecordCopyValue(person, kABPersonJobTitleProperty);

//读取department部门

NSString *department = (__bridge NSString*)ABRecordCopyValue(person, kABPersonDepartmentProperty);

//读取birthday生日

NSDate *birthday = (__bridge NSDate*)ABRecordCopyValue(person, kABPersonBirthdayProperty);

//读取note备忘录

NSString *note = (__bridge NSString*)ABRecordCopyValue(person, kABPersonNoteProperty);

//第一次添加该条记录的时间

NSString *firstknow = (__bridge NSString*)ABRecordCopyValue(person, kABPersonCreationDateProperty);

NSLog(@"第一次添加该条记录的时间%@\n",firstknow);

//最后一次修改該条记录的时间

NSString *lastknow = (__bridge NSString*)ABRecordCopyValue(person, kABPersonModificationDateProperty);

NSLog(@"最后一次修改該条记录的时间%@\n",lastknow);

// 名字

NSLog(@"%@ %@", firstName, lastName);

//获取email多值

ABMultiValueRef email = ABRecordCopyValue(person, kABPersonEmailProperty);

int emailcount = ABMultiValueGetCount(email);

for (int x = 0; x < emailcount; x++)

{

//获取email Label

NSString* emailLabel = (__bridge NSString*)ABAddressBookCopyLocalizedLabel(ABMultiValueCopyLabelAtIndex(email, x));

//获取email值

NSString* emailContent = (__bridge NSString*)ABMultiValueCopyValueAtIndex(email, x);

}

//读取地址多值

ABMultiValueRef address = ABRecordCopyValue(person, kABPersonAddressProperty);

int count = ABMultiValueGetCount(address);

for(int j = 0; j < count; j++)

{

//获取地址Label

NSString* addressLabel = (__bridge NSString*)ABMultiValueCopyLabelAtIndex(address, j);

//获取該label下的地址6属性

NSDictionary* personaddress =(__bridge NSDictionary*) ABMultiValueCopyValueAtIndex(address, j);

NSString* country = [personaddress valueForKey:(NSString *)kABPersonAddressCountryKey];

NSString* city = [personaddress valueForKey:(NSString *)kABPersonAddressCityKey];

NSString* state = [personaddress valueForKey:(NSString *)kABPersonAddressStateKey];

NSString* street = [personaddress valueForKey:(NSString *)kABPersonAddressStreetKey];

NSString* zip = [personaddress valueForKey:(NSString *)kABPersonAddressZIPKey];

NSString* coutntrycode = [personaddress valueForKey:(NSString *)kABPersonAddressCountryCodeKey];

}

//获取dates多值

ABMultiValueRef dates = ABRecordCopyValue(person, kABPersonDateProperty);

int datescount = ABMultiValueGetCount(dates);

for (int y = 0; y < datescount; y++)

{

//获取dates Label

NSString* datesLabel = (__bridge NSString*)ABAddressBookCopyLocalizedLabel(ABMultiValueCopyLabelAtIndex(dates, y));

//获取dates值

NSString* datesContent = (__bridge NSString*)ABMultiValueCopyValueAtIndex(dates, y);

}

//获取kind值

CFNumberRef recordType = ABRecordCopyValue(person, kABPersonKindProperty);

if (recordType == kABPersonKindOrganization) {

// it‘s a company

NSLog(@"it‘s a company\n");

} else {

// it‘s a person, resource, or room

NSLog(@"it‘s a person, resource, or room\n");

}

//获取IM多值

ABMultiValueRef instantMessage = ABRecordCopyValue(person, kABPersonInstantMessageProperty);

for (int l = 1; l < ABMultiValueGetCount(instantMessage); l++)

{

//获取IM Label

NSString* instantMessageLabel = (__bridge NSString*)ABMultiValueCopyLabelAtIndex(instantMessage, l);

//获取該label下的2属性

NSDictionary* instantMessageContent =(__bridge NSDictionary*) ABMultiValueCopyValueAtIndex(instantMessage, l);

NSString* username = [instantMessageContent valueForKey:(NSString *)kABPersonInstantMessageUsernameKey];

NSString* service = [instantMessageContent valueForKey:(NSString *)kABPersonInstantMessageServiceKey];

}

//读取电话多值

ABMultiValueRef phone = ABRecordCopyValue(person, kABPersonPhoneProperty);

for (int k = 0; k<ABMultiValueGetCount(phone); k++)

{

//获取电话Label

NSString * personPhoneLabel = (__bridge NSString*)ABAddressBookCopyLocalizedLabel(ABMultiValueCopyLabelAtIndex(phone, k));

//获取該Label下的电话值

NSString * personPhone = (__bridge NSString*)ABMultiValueCopyValueAtIndex(phone, k);

NSLog(@"--电话%@", personPhone);

}

//获取URL多值

ABMultiValueRef url = ABRecordCopyValue(person, kABPersonURLProperty);

for (int m = 0; m < ABMultiValueGetCount(url); m++)

{

//获取电话Label

NSString * urlLabel = (__bridge NSString*)ABAddressBookCopyLocalizedLabel(ABMultiValueCopyLabelAtIndex(url, m));

//获取該Label下的电话值

NSString * urlContent = (__bridge NSString*)ABMultiValueCopyValueAtIndex(url,m);

NSLog(@"url:%@", urlContent);

}

//读取照片

NSData *image = (__bridge NSData*)ABPersonCopyImageData(person);

}

}

iOS9

在iOS9中,apple终于解决了这个问题,全新的Contacts Framework将完全替代AddressBookFramework。

一、联系人对象CNContact

创建CNMutableContact对象:

 CNMutableContact * contact = [[CNMutableContact alloc] init];

设置联系人头像:

contact.imageData = UIImagePNGRepresentation([UIImage imageNamed:@"Icon.png"]);

设置联系人姓名:

//设置名字
contact.givenName = @"stephen";
//设置姓氏
contact.familyName = @"zhuang";

设置联系人邮箱:

CNLabeledValue *homeEmail = [CNLabeledValue labeledValueWithLabel:CNLabelHome value:@"[email protected]"];
CNLabeledValue *workEmail =[CNLabeledValue labeledValueWithLabel:CNLabelWork value:@"[email protected]"];
contact.emailAddresses = @[homeEmail,workEmail];

这里需要注意,emailAddresses属性是一个数组,数组中是才CNLabeledValue对象,CNLabeledValue对象主要用于创建一些联系人属性的键值对应,通过这些对应,系统会帮我们进行数据的格式化,例如CNLabelHome,就会将号码格式成家庭邮箱的格式,相应的其他键如下:

//家庭
CONTACTS_EXTERN NSString * const CNLabelHome                             NS_AVAILABLE(10_11, 9_0);
//工作
CONTACTS_EXTERN NSString * const CNLabelWork                             NS_AVAILABLE(10_11, 9_0);
//其他
CONTACTS_EXTERN NSString * const CNLabelOther                            NS_AVAILABLE(10_11, 9_0);

// 邮箱地址
CONTACTS_EXTERN NSString * const CNLabelEmailiCloud                      NS_AVAILABLE(10_11, 9_0);

// url地址
CONTACTS_EXTERN NSString * const CNLabelURLAddressHomePage               NS_AVAILABLE(10_11, 9_0);

// 日期
CONTACTS_EXTERN NSString * const CNLabelDateAnniversary                  NS_AVAILABLE(10_11, 9_0);

设置联系人电话:

contact.phoneNumbers = @[[CNLabeledValue labeledValueWithLabel:CNLabelPhoneNumberiPhone value:[CNPhoneNumber phoneNumberWithStringValue:@"12344312321"]]];

联系人电话的配置方式和邮箱类似,键值如下:

CONTACTS_EXTERN NSString * const CNLabelPhoneNumberiPhone                NS_AVAILABLE(10_11, 9_0);
CONTACTS_EXTERN NSString * const CNLabelPhoneNumberMobile                NS_AVAILABLE(10_11, 9_0);
CONTACTS_EXTERN NSString * const CNLabelPhoneNumberMain                  NS_AVAILABLE(10_11, 9_0);
CONTACTS_EXTERN NSString * const CNLabelPhoneNumberHomeFax               NS_AVAILABLE(10_11, 9_0);
CONTACTS_EXTERN NSString * const CNLabelPhoneNumberWorkFax               NS_AVAILABLE(10_11, 9_0);
CONTACTS_EXTERN NSString * const CNLabelPhoneNumberOtherFax              NS_AVAILABLE(10_11, 9_0);
CONTACTS_EXTERN NSString * const CNLabelPhoneNumberPager                 NS_AVAILABLE(10_11, 9_0);

设置联系人地址:

CNMutablePostalAddress * homeAdress = [[CNMutablePostalAddress alloc]init];
homeAdress.street = @"";
homeAdress.city = @"";
homeAdress.state = @"";
homeAdress.postalCode = @"";
contact.postalAddresses = @[[CNLabeledValue labeledValueWithLabel:CNLabelHome value:homeAdress]];

设置生日:

NSDateComponents * birthday = [[NSDateComponents  alloc]init];
birthday.day=2;
birthday.month=11;
birthday.year=1989;
contact.birthday=birthday;

二、联系人请求: CNSaveRequest

   //初始化方法
    CNSaveRequest * saveRequest = [[CNSaveRequest alloc]init];
    //添加联系人
    [saveRequest addContact:contact toContainerWithIdentifier:nil];
@interface CNSaveRequest : NSObject
//添加一个联系人
- (void)addContact:(CNMutableContact *)contact toContainerWithIdentifier:(nullable NSString *)identifier;
//更新一个联系人
- (void)updateContact:(CNMutableContact *)contact;
//删除一个联系人
- (void)deleteContact:(CNMutableContact *)contact;
//添加一组联系人
- (void)addGroup:(CNMutableGroup *)group toContainerWithIdentifier:(nullable NSString *)identifier;
//更新一组联系人
- (void)updateGroup:(CNMutableGroup *)group;
//删除一组联系人
- (void)deleteGroup:(CNMutableGroup *)group;
//向组中添加子组
- (void)addSubgroup:(CNGroup *)subgroup toGroup:(CNGroup *)group NS_AVAILABLE(10_11, NA);
//在组中删除子组
- (void)removeSubgroup:(CNGroup *)subgroup fromGroup:(CNGroup *)group NS_AVAILABLE(10_11, NA);
//向组中添加成员
- (void)addMember:(CNContact *)contact toGroup:(CNGroup *)group;
//向组中移除成员
- (void)removeMember:(CNContact *)contact fromGroup:(CNGroup *)group;
@end

写入操作:

CNContactStore * store = [[CNContactStore alloc]init];
[store executeSaveRequest:saveRequest error:nil];

三、获取联系人信息

    // 创建通信录对象
    CNContactStore *contactStore = [[CNContactStore alloc] init];

    // 创建获取通信录的请求对象
    // 拿到所有打算获取的属性对应的key
    NSArray *keys = @[CNContactGivenNameKey, CNContactFamilyNameKey, CNContactPhoneNumbersKey];

    // 创建CNContactFetchRequest对象
    CNContactFetchRequest *request = [[CNContactFetchRequest alloc] initWithKeysToFetch:keys];

    // 遍历所有的联系人
    [contactStore enumerateContactsWithFetchRequest:request error:nil usingBlock:^(CNContact * _Nonnull contact, BOOL * _Nonnull stop) {
        // 获取联系人的姓名
        NSString *lastname = contact.familyName;
        NSString *firstname = contact.givenName;
        NSLog(@"%@ %@", lastname, firstname);

        // 获取联系人的电话号码
        NSArray *phoneNums = contact.phoneNumbers;
        for (CNLabeledValue *labeledValue in phoneNums) {
            // 获取电话号码的KEY
            NSString *phoneLabel = labeledValue.label;

            // 获取电话号码
            CNPhoneNumber *phoneNumer = labeledValue.value;
            NSString *phoneValue = phoneNumer.stringValue;

            NSLog(@"%@ %@", phoneLabel, phoneValue);
            ZXPersonTemp *person = [[ZXPersonTemp alloc] init];
            person.name = [NSString stringWithFormat:@"%@%@",lastname,firstname];
            person.phone = phoneValue;
            [_addressBookArray addObject:person];
        }
    }];

四、选择联系人

- (void)insertNewObject:(id)sender {
    CNContactPickerViewController * con = [[CNContactPickerViewController alloc] init];
    con.delegate = self;
    [self presentViewController:con animated:YES completion:nil];
}

- (void)contactPicker:(CNContactPickerViewController *)picker didSelectContactProperty:(nonnull CNContactProperty *)contactProperty
{
    CNContact *contact = contactProperty.contact;
    CNPhoneNumber *phoneNumer = contactProperty.value;
    NSString *phoneValue = phoneNumer.stringValue;
    NSString *lastname = contact.familyName;
    NSString *firstname = contact.givenName;
    ZXPersonTemp *person = [[ZXPersonTemp alloc] init];
    person.name = [NSString stringWithFormat:@"%@%@",lastname,firstname];
    person.phone = phoneValue;
    [_addressBookArray insertObject:person atIndex:0];
    [self.tableView insertRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:0 inSection:0]] withRowAnimation:UITableViewRowAnimationAutomatic];
    [picker dismissViewControllerAnimated:YES completion:nil];
}

(原文中 iOS9以下 获取通讯录 类型强转时加 __bridge)

文/千煌89(简书作者)
原文链接:http://www.jianshu.com/p/6acad14cf3c9
著作权归作者所有,转载请联系作者获得授权,并标注“简书作者”。

时间: 2024-11-13 05:35:02

关于通讯录的相关文章

ios-私人通讯录 页面间的跳转和传值

这个demo 有多个页面 并涉及顺传和逆传 而且还有一个第三方库的导入 来实现自定义提示消息的特效 利用代理来实现页面间的传值 一个页面代表一个controller 这次  ViewController  反而一句代码都没写 // // HMContact.h // 私人通讯录 // // Created by YaguangZhu on 15/9/6. // Copyright (c) 2015年 YaguangZhu. All rights reserved. // #import <Fou

ObjectC----实现简单的通讯录(增删改查)

// Created By 郭仔 2015年04月09日21:27:50 经过两天的低迷,状态在慢慢的回归了,生活还要继续,人生还需奋斗! 祝:好人一生平安!!! ======================================================================== 题目描述: 1.创建AddressBook类. 1)使?用字典作为容器,字典的Key值为分组名(姓名?首字?母,?大写),value值为数组,数组 中存放联系?人(Person实例).(5分

C语言写郑州大学校友通讯录

1 #include <stdio.h> 2 #include <string.h> 3 #include <stdlib.h> 4 #define LEN sizeof(struct address_list) 5 6 /* 7 *************************通讯录结构体*********************************** 8 */ 9 10 struct address_list 11 { 12 char name[30]; /

Java企业微信开发_03_通讯录同步

一.本节要点 1.获取通讯录密钥 获取方式: 登录企业微信—>管理工具—>通讯录同步助手—>开启“API接口同步”  ; 开启后,即可看到通讯录密钥,也可设置通讯录API的权限:读取或者编辑通讯录. 获取通讯录密钥的目的: 通过企业ID(CorpId)和 通讯录密钥可以获取通讯录相关接口的使用凭证(AccessToken).有了AccessToken,就可以使用通讯录相关接口了. 凭证的获取方式有两种(此处暂时存疑,以待勘误): 通讯录AccessToken:CorpId+通讯录密钥 其

数据库连接学习--简单的通讯录

为了做毕业设计,学习了Java,然后就要连接数据库,为了连接数据库就学习做了一个简单的小项目,通讯录(现在只有添加的功能),成功连接数据库 首先看看我的WEB首页吧: 比较简单,然后是填加联系人页面 我的数据库连接的代码先抛出来,毕竟这是我做通讯录学习的重点, package s2.jsp.zhangxiao.dao; import java.sql.PreparedStatement; import java.sql.Connection; import java.sql.ResultSet;

通讯录程序

#通讯录程序 print('|---欢迎进入通讯录程序---|') print('|---1:查询联系人资料---|') print('|---2:插入新的联系人---|') print('|---3:删除已有联系人---|') print('|---4:退出通讯录程序---|') address=dict() while True: print('请输入相关指令代码:',end='') enter=int(input()) if enter == 1: print('请输入姓名:',end='

C#通讯录——Windows Form Contact List

C#通讯录 Windows Form Contact List 主窗口 using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using Syste

通讯录--(适配iOS7/8/9)

导入库#import <AddressBook/AddressBook.h> #import <AddressBookUI/AddressBookUI.h> #pragma mark  点击 弹出通讯录 - (IBAction)contactClicked:(id)sender { //1. 创建联系人选择控制器 ABPeoplePickerNavigationController *picker = [ABPeoplePickerNavigationController new]

通讯录--(iOS9独有的方法)

导入库文件   #import <ContactsUI/ContactsUI.h> #pragma mark iOS9 新出的点击通讯录的获取信息的办法 #pragma mark - 先弹出联系人控制器 - (IBAction)ios9Clicked:(id)sender { // 1. 创建控制器 CNContactPickerViewController * picker = [CNContactPickerViewController new]; // 2. 设置代理 picker.de

【Android 仿微信通讯录 导航分组列表-上】使用ItemDecoration为RecyclerView打造带悬停头部的分组列表

[Android 仿微信通讯录 导航分组列表-上]使用ItemDecoration为RecyclerView打造带悬停头部的分组列表 一 概述 本文是Android导航分组列表系列上,因时间和篇幅原因分上下,最终上下合璧,完整版效果如下: 上部残卷效果如下:两个ItemDecoration,一个实现悬停头部分组列表功能,一个实现分割线(官方demo) 网上关于实现带悬停分组头部的列表的方法有很多,像我看过有主席的自定义ExpandListView实现的,也看过有人用一个额外的父布局里面套 Rec