iOS通讯录相关知识-浅析

本文来自于:贞娃儿的博客  http://blog.sina.com.cn/zhenwawaer

在开发一些应用中,我们如果需要iPhone设备中的通讯录信息。或者,需要开发通讯录相关的一些功能。那么就需要了解一下iOS中关于通讯录编程的相关知识。

一、AddressBook.framework-通讯录框架

关于通讯录的相关操作,被集成在AddressBook.framework框架中。所以,我们在使用通讯录相关功能的时候,需要在项目中引入AddressBook.framework框架。并且在需要使用的地方,加入框架头文件:

#import

二、通讯录操作相关知识

先贴一贴:

- (void)viewDidLoad

{

[super viewDidLoad];

// 获得用户通讯录数据的一个引用

ABAddressBookRef addressBook = ABAddressBookCreate();

if (addressBook != nil){

NSLog(@"Successfully accessed the address book.");

// 查看通讯录状态:YES:通讯录改变,但还没有保存;NO;通讯录不需要保存

if (ABAddressBookHasUnsavedChanges(addressBook)){

BOOL doYouWantToSaveChanges = YES;

if (doYouWantToSaveChanges){

CFErrorRef saveError = NULL;

// 保存通讯录

if (ABAddressBookSave(addressBook, &saveError)){

// 保存成功

} else {

// 保存失败,查看CFErrorRef 来了解错误原因

}

} else {

// 放弃保存

ABAddressBookRevert(addressBook);

}

}else{

NSLog(@"No changes to the address book.");

}

CFRelease(addressBook);// 释放通讯录引用对象

} else {

NSLog(@"Could not access the address book.");

}

}

解释:有很多的类和知识点,需要mark一下。

1.获取通讯录的应用:

ABAddressBookRef addressBook = ABAddressBookCreate();

在使用完成后,需要释放:

CFRelease(addressBook);

因为:ABAddressBookCreate 函数返回的数据库实例,在使用完后必须将它释放掉,可以使用 CFRelease Core Foundation 方法。

2.保存修改和放弃修改:

ABAddressBookSave(addressBook, &saveError)// 保存

ABAddressBookRevert(addressBook);// 放弃保存

三、获得通讯录的所有联系人数据

直接贴:

- (void)viewDidLoad

{

[super viewDidLoad];

ABAddressBookRef addressBook = ABAddressBookCreate();// 获得用户通讯录数据的一个引用

if (addressBook != nil){

NSLog(@"Successfully accessed the address book.");

// 返回通讯录中所有的数据

NSArray *arrayOfAllPeople = ( NSArray *) ABAddressBookCopyArrayOfAllPeople(addressBook);

// 循环所有联系人数据

for (NSUInteger peopleCounter = 0; peopleCounter < [arrayOfAllPeople count]; peopleCounter++){

ABRecordRef thisPerson = (ABRecordRef)[arrayOfAllPeople objectAtIndex:peopleCounter];

NSLog(@"%@", thisPerson);

NSString *firstName = (NSString *) ABRecordCopyValue(thisPerson, kABPersonFirstNameProperty);

NSString *lastName = (NSString *) ABRecordCopyValue(thisPerson, kABPersonLastNameProperty);

NSLog(@"First Name = %@", firstName);

NSLog(@"Last Name = %@", lastName);

[self logPersonEmails:thisPerson];

}

CFRelease(addressBook);// 释放通讯录引用对象

}

}

// 邮箱的数据

- (void) logPersonEmails:(ABRecordRef)paramPerson{

if (paramPerson == NULL){

NSLog(@"The given person is NULL.");

return;

}

// 获得电子邮件数据,电子邮件是个多值属性,所以需要循环遍历

ABMultiValueRef emails =ABRecordCopyValue(paramPerson, kABPersonEmailProperty);

if (emails == NULL){

NSLog(@"This contact does not have any emails.");

return;

}

for (NSUInteger emailCounter = 0;emailCounter < ABMultiValueGetCount(emails);emailCounter++){

// 邮件类别

NSString *emailLabel = [(NSString *) ABMultiValueCopyLabelAtIndex(emails, emailCounter) autorelease];

NSString *localizedEmailLabel = [(NSString *) ABAddressBookCopyLocalizedLabel((CFStringRef)emailLabel) autorelease];

// 邮件值

NSString *emailValue=[(NSString *)ABMultiValueCopyValueAtIndex(emails, emailCounter) autorelease];

NSString *email = [NSString stringWithFormat:@"Label = %@, Localized Label = %@,Email = %@",emailLabel,localizedEmailLabel,emailValue];

NSLog(@"%@",email);

}

CFRelease(emails);

}

解释:

1.在通讯录中,有单值和多值的区分

单值:在某一项中,只有一个值,比如:kABPersonFirstNameProperty和kABPersonLastNameProperty等

多值:kABPersonEmailProperty等

这样的话,我们遍历的时候,必须要区别对待了。

2.数据的释放

获得相关信息的方法为:XXXCopyXXX方法,所以,我们必须要手动释放数据,或者使用autorelease。

四、向通讯录中添加联系人-ABPersonCreate

贴代码:

- (void)viewDidLoad

{

[super viewDidLoad];

ABAddressBookRef addressBook = ABAddressBookCreate();// 获得用户通讯录数据的一个引用

if (addressBook != NULL){

ABRecordRef anthonyRobbins = [self newPersonWithFirstName:@"TT"

lastName:@"DD"

inAddressBook:addressBook];

if (anthonyRobbins != NULL){

NSLog(@"添加成功!");

CFRelease(anthonyRobbins);

}

CFRelease(addressBook);

}

}

// 添加联系人到通讯录

- (ABRecordRef) newPersonWithFirstName:(NSString *)paramFirstName lastName:(NSString *)paramLastName inAddressBook:(ABAddressBookRef)paramAddressBook{

ABRecordRef result = NULL;

if (paramAddressBook == NULL){

NSLog(@"The address book is NULL.");

return NULL;

}

if ([paramFirstName length] == 0 && [paramLastName length] == 0){

NSLog(@"First name and last name are both empty.");

return NULL;

}

result = ABPersonCreate();// 创建一个新的联系人

if (result == NULL){

NSLog(@"Failed to create a new person.");

return NULL;

}

BOOL couldSetFirstName = NO;

BOOL couldSetLastName = NO;

CFErrorRef setFirstNameError = NULL;

CFErrorRef setLastNameError = NULL;

// 设置FirstName,并且返回是否设置成功

couldSetFirstName = ABRecordSetValue(result,kABPersonFirstNameProperty,(CFTypeRef)paramFirstName,&setFirstNameError);

// 设置LastName,并且返回是否设置成功

couldSetLastName = ABRecordSetValue(result, kABPersonLastNameProperty,(CFTypeRef)paramLastName,&setLastNameError);

// 设置其他属性,类似,但是还没有研究出来先mark一下吧

if (couldSetFirstName && couldSetLastName){

NSLog(@"Successfully set the first name and the last name of the person.");

} else {

NSLog(@"Failed to set the first name and/or last name of the person.");

}

CFErrorRef couldAddPersonError = NULL;

BOOL couldAddPerson = ABAddressBookAddRecord(paramAddressBook, result,&couldAddPersonError);

if (couldAddPerson){

NSLog(@"添加联系人-成功!");

} else {

NSLog(@"添加联系人-失败!");

CFRelease(result);

result = NULL;

return result;

}

// 更新通讯录

if (ABAddressBookHasUnsavedChanges(paramAddressBook)){

CFErrorRef couldSaveAddressBookError = NULL;

BOOL couldSaveAddressBook = ABAddressBookSave(paramAddressBook, &couldSaveAddressBookError);

if (couldSaveAddressBook){

NSLog(@"成功的保存到了通讯录中");

} else {

NSLog(@"保存到通讯录中失败");

}

}

return result;

}

大概步骤:

1.创建通讯录的引用

ABAddressBookRef addressBook = ABAddressBookCreate();

2.创建联系人

ABRecordRef result = NULL;

result = ABPersonCreate();// 创建一个新的联系人

3.并联系人中添加相关的值

ABRecordSetValue(result, kABPersonLastNameProperty,(CFTypeRef)paramLastName,&setLastNameError);

添加的项,应该也要分单值和多值的情况。现在还没搞清楚多值类型(电话号码,电子邮件)如何添加。如果您知道或者了解,请不吝赐教!谢谢!

4.将联系人加入到通讯录中

CFErrorRef couldAddPersonError = NULL;

BOOL couldAddPerson = ABAddressBookAddRecord(paramAddressBook, result,&couldAddPersonError);

5.保存通讯录

// 更新通讯录

if (ABAddressBookHasUnsavedChanges(paramAddressBook)){

CFErrorRef couldSaveAddressBookError = NULL;

BOOL couldSaveAddressBook = ABAddressBookSave(paramAddressBook, &couldSaveAddressBookError);

}

五、向通讯录中添加分组-ABGroupCreate

贴:

- (void)viewDidLoad

{

[super viewDidLoad];

ABAddressBookRef addressBook = ABAddressBookCreate();// 获得用户通讯录数据的一个引用

if (addressBook != nil){

ABRecordRef personalCoachesGroup =[self newGroupWithName:@"测试分类"

inAddressBook:addressBook];

if (personalCoachesGroup != NULL){

NSLog(@"Successfully created the group.");

CFRelease(personalCoachesGroup);

} else {

NSLog(@"Could not create the group.");

}

CFRelease(addressBook);

}

}

// 添加群组到通讯录中

- (ABRecordRef) newGroupWithName:(NSString *)paramGroupName inAddressBook:(ABAddressBookRef)paramAddressBook{

ABRecordRef result = NULL;

if (paramAddressBook == NULL){

NSLog(@"The address book is nil.");

return NULL;

}

result = ABGroupCreate();// 创建一个分组

if (result == NULL){

NSLog(@"Failed to create a new group.");

return NULL;

}

BOOL couldSetGroupName = NO;

CFErrorRef error = NULL;

// 设置分组

couldSetGroupName = ABRecordSetValue(result, kABGroupNameProperty,(CFTypeRef)paramGroupName,&error);

if (couldSetGroupName){

BOOL couldAddRecord = NO;

CFErrorRef couldAddRecordError = NULL;

couldAddRecord = ABAddressBookAddRecord(paramAddressBook, result,&couldAddRecordError);

if (couldAddRecord){

NSLog(@"Successfully added the new group.");

if (ABAddressBookHasUnsavedChanges(paramAddressBook)){

BOOL couldSaveAddressBook = NO;

CFErrorRef couldSaveAddressBookError = NULL;

couldSaveAddressBook = ABAddressBookSave(paramAddressBook,&couldSaveAddressBookError);

if (couldSaveAddressBook){

NSLog(@"Successfully saved the address book.");

} else {

CFRelease(result);

result = NULL;

NSLog(@"Failed to save the address book.");

}

} else {

CFRelease(result);

result = NULL;

NSLog(@"No unsaved changes.");

}

} else {

CFRelease(result);

result = NULL;

NSLog(@"Could not add a new group.");

}

} else {

CFRelease(result);

result = NULL;

NSLog(@"Failed to set the name of the group."); }

return result;

}

大概步骤:

1.创建通讯录的引用

ABAddressBookRef addressBook = ABAddressBookCreate();

2.创建分组

ABRecordRef result = NULL;

result = ABGroupCreate();// 创建一个分组

3.并分组中添加相关的值

// 设置分组

couldSetGroupName = ABRecordSetValue(result, kABGroupNameProperty,(CFTypeRef)paramGroupName,&error);

4.将分组加入到通讯录中

CFErrorRef couldAddRecordError = NULL;

couldAddRecord = ABAddressBookAddRecord(paramAddressBook, result,&couldAddRecordError);

5.保存通讯录

// 更新通讯录

if (ABAddressBookHasUnsavedChanges(paramAddressBook)){

CFErrorRef couldSaveAddressBookError = NULL;

BOOL couldSaveAddressBook = ABAddressBookSave(paramAddressBook, &couldSaveAddressBookError);

}

六、将联系人添加到指定的分组中

有了前面的铺垫,我们就清楚了。不解释了!

贴:

ABAddressBookRef addressBook = ABAddressBookCreate();

if (addressBook != nil){

// 创建联系人

ABRecordRef richardBranson = [self newPersonWithFirstName:@"Richard"

lastName:@"Branson"

inAddressBook:addressBook];

if (richardBranson != NULL){

// 创建分组

ABRecordRef entrepreneursGroup = [self newGroupWithName:@"Entrepreneurs"

inAddressBook:addressBook];

if (entrepreneursGroup != NULL){

BOOL isSuccess=[self addPerson:richardBranson toGroup:entrepreneursGroup saveToAddressBook:addressBook];

if (isSuccess){

NSLog(@"Successfully");

} else {

NSLog(@"Failed ");

}

CFRelease(entrepreneursGroup);

} else {

NSLog(@"Failed to create the Entrepreneurs group.");

}

CFRelease(richardBranson);

} else {

NSLog(@"Failed to create an entity for Richard Branson."); }

CFRelease(addressBook);

} else {

NSLog(@"Address book is nil.");

}

// 把联系人添加到指定的组中

- (BOOL) addPerson:(ABRecordRef)paramPerson toGroup:(ABRecordRef)paramGroup saveToAddressBook:(ABAddressBookRef)paramAddressBook{

BOOL result = NO;

if (paramPerson == NULL ||paramGroup == NULL || paramAddressBook == NULL){

NSLog(@"Invalid parameters are given.");

return result;

}

CFErrorRef error = NULL;

result = ABGroupAddMember(paramGroup,paramPerson,&error);

if (result == NO){

NSLog(@"Could not add the person to the group.");

return result;

}

if (ABAddressBookHasUnsavedChanges(paramAddressBook)){

BOOL couldSaveAddressBook = NO;

CFErrorRef couldSaveAddressBookError = NULL;

couldSaveAddressBook = ABAddressBookSave(paramAddressBook, &couldSaveAddressBookError);

if (couldSaveAddressBook){

NSLog(@"Successfully added the person to the group.");

result = YES;

} else {

NSLog(@"Failed to save the address book.");

}

} else {

NSLog(@"No changes were saved.");

}

return result;

}

七、查找联系人和分组

比如我们可能需要查找通讯录的某个分组或者联系人是否存在,可以使用以下方法:

贴:

#pragma mark - 查找通讯录

// 查找通讯录中联系人是否存在指定联系人

- (BOOL) doesPersonExistWithFirstName:(NSString *)paramFirstName lastName:(NSString *)paramLastName inAddressBook:(ABRecordRef)paramAddressBook{

BOOL result = NO;

if (paramAddressBook == NULL){

NSLog(@"The address book is null.");

return NO;

}

NSArray *allPeople = [(NSArray *) ABAddressBookCopyArrayOfAllPeople(paramAddressBook) autorelease];

NSUInteger peopleCounter = 0;

for (peopleCounter = 0; peopleCounter < [allPeople count]; peopleCounter++){

ABRecordRef person = (ABRecordRef)[allPeople objectAtIndex:peopleCounter];

NSString *firstName = [(NSString *) ABRecordCopyValue(person, kABPersonFirstNameProperty) autorelease];

NSString *lastName = [(NSString *) ABRecordCopyValue(person, kABPersonLastNameProperty) autorelease];

BOOL firstNameIsEqual = NO;

BOOL lastNameIsEqual = NO;

if ([firstName length] == 0 && [paramFirstName length] == 0){

firstNameIsEqual = YES;

}else if ([firstName isEqualToString:paramFirstName]){

firstNameIsEqual = YES;

}

if ([lastName length] == 0 &&[paramLastName length] == 0){

lastNameIsEqual = YES;

}else if ([lastName isEqualToString:paramLastName]){

lastNameIsEqual = YES;

}

if (firstNameIsEqual && lastNameIsEqual){

return YES;

}

}

return result;

}

// 查找通讯录中是否存在是某个分组

- (BOOL) doesGroupExistWithGroupName:(NSString *)paramGroupName inAddressBook:(ABAddressBookRef)paramAddressBook{

BOOL result = NO;

if (paramAddressBook == NULL){

NSLog(@"The address book is null.");

return NO;

}

NSArray *allGroups = [( NSArray *) ABAddressBookCopyArrayOfAllGroups(paramAddressBook) autorelease];

NSUInteger groupCounter = 0;

for (groupCounter = 0; groupCounter < [allGroups count];groupCounter++){

ABRecordRef group = ( ABRecordRef) [allGroups objectAtIndex:groupCounter];

NSString *groupName = [( NSString *) ABRecordCopyValue(group, kABGroupNameProperty) autorelease];

if ([groupName length] == 0 &&[paramGroupName length] == 0){

return YES;

}else if ([groupName isEqualToString:paramGroupName]){

return YES;

}

}

return result;

}

// 根据姓名,模糊查询

- (BOOL) doesPersonExistWithFullName:(NSString *)paramFullName inAddressBook:(ABAddressBookRef)paramAddressBook{

BOOL result = NO;

if (paramAddressBook == NULL){

NSLog(@"Address book is null.");

return NO;

}

NSArray *allPeopleWithThisName = [( NSArray *) ABAddressBookCopyPeopleWithName(paramAddressBook, (CFStringRef)paramFullName) autorelease];

if ([allPeopleWithThisName count] > 0){

result = YES;

}

return result;

}

八、设置和获得联系人图片信息

#pragma mark - 通讯录图片相关

// 获得联系人的头像

- (UIImage *) getPersonImage:(ABRecordRef)paramPerson{ UIImage *result = nil;

if (paramPerson == NULL){

NSLog(@"The person is nil.");

return NULL;

}

NSData *imageData = [( NSData *) ABPersonCopyImageData(paramPerson) autorelease];

if (imageData != nil){

UIImage *image = [UIImage imageWithData:imageData];

result = image;

}

return result;

}

// 设置联系人的头像

- (BOOL) setPersonImage:(ABRecordRef)paramPerson inAddressBook:(ABAddressBookRef)paramAddressBook withImageData:(NSData *)paramImageData{

BOOL result = NO;

if (paramAddressBook == NULL){

NSLog(@"The address book is nil.");

return NO;

}

if (paramPerson == NULL){

NSLog(@"The person is nil.");

return NO;

}

CFErrorRef couldSetPersonImageError = NULL;

BOOL couldSetPersonImage = ABPersonSetImageData(paramPerson,(CFDataRef)paramImageData, &couldSetPersonImageError);

if (couldSetPersonImage){

NSLog(@"Successfully set the person‘s image. Saving...");

if (ABAddressBookHasUnsavedChanges(paramAddressBook)){

BOOL couldSaveAddressBook = NO;

CFErrorRef couldSaveAddressBookError = NULL;

couldSaveAddressBook = ABAddressBookSave(paramAddressBook, &couldSaveAddressBookError);

if (couldSaveAddressBook){

NSLog(@"Successfully saved the address book.");

result = YES;

} else {

NSLog(@"Failed to save the address book.");

}

} else {

NSLog(@"There are no changes to be saved!"); }

} else {

NSLog(@"Failed to set the person‘s image.");

}

return result;

}

解释:

获得头像信息:ABPersonCopyImageData方法

设置头像信息:ABPersonSetImageData方法

iOS通讯录相关知识-浅析

时间: 2024-10-11 21:21:08

iOS通讯录相关知识-浅析的相关文章

iOS网络相关知识总结

iOS网络相关知识总结 1.关于请求NSURLRequest? 我们经常讲的GET/POST/PUT等请求是指我们要向服务器发出的NSMutableURLRequest的类型; 我们可以设置Request的URL, HTTPMethod, HTTPHeader, HTTPBody等信息.一般发请求尽量不要使用NSURLRequest,因为它不能设置请求方式.请求超时等(总之什么都不能设置).通常发请求都使用NSMutableURLRequest,可以进行更多的设置. 补充1:因为NSURL不支持

一文让你彻底了解iOS字体相关知识

作者:董铂然 授权本站转载. 写本文的契机主要是把自己整理的关于iOS字体方面的知识不断更新写在这篇博文中,用来自己以后查阅. 一.iOS原生字体展示 在 label中选择字体的font,并把font由system改成custom后,就能在family中看到72种特殊字体.这些里面就有很炫的字体,但 是全部是只针对英文数字,对中文无效.写了一个程序把所有的原生样式遍历出来展示可以达到如下效果.可以清楚地看到每个字体对应的样式,不用再一个个试 了. 如果你不是在董铂然博客园看到本文,请点击查看原文

iOS地图相关知识总结

p.p1 { margin: 0.0px 0.0px 0.0px 0.0px; font: 18.0px "PingFang SC"; color: #000000 } p.p2 { margin: 0.0px 0.0px 0.0px 0.0px; font: 14.0px "PingFang SC Semibold"; color: #ed719e } p.p3 { margin: 0.0px 0.0px 0.0px 0.0px; font: 14.0px &qu

转 iOS:ARC相关知识,assign/copy/retain/strong/weak/readyonly/readwrite/nonatomic/atomic

    自动引用计数 ARC不是垃圾回收,而是编译器自动插入代码来减少程序员的代码输入和失误.     同时比垃圾和效率要高,因为其不影响运行时间,相当于自己管理内存.     总是通过属性来管理实例变量(init/dealloc除外),在dealloc中释放所有属性. dealloc中会自动加入释放实例变量的代码,因此不必要手段增加释放实例变量的代码.不需要手动调用[super  dealloc]   不要调用retain,release,autorelease,编译器会自动插入相关代码. 注

iOS底层基础知识-文件目录结构

一:iOS沙盒知识 出于安全考虑,iOS系统把每个应用以及数据都放到一个沙盒(sandbox)里面,应用只能访问自己沙盒目录里面的文件.网络资源等(也有例外,比如系统通讯录.照相机.照片等能在用户授权的情况下被第三方应用访问) 1:MyApp.app 该目录包含了应用程序本身的数据,程序打包的时候的资源文件和一些本地文件就是存放在这个目录下的. 程序的可执行程序.plist文件也在这个目录下. 这个目录不会被iTunes同步 2:Documents 使用这个目录来保存关键数据.关键数据指那些应用

iOS开发基础知识--碎片42

iOS开发基础知识--碎片42  iOS开发基础知识--碎片42 1:报thread 1:exc_bad_access(code=1,address=0x70********) 闪退 这种错误通常是内存管理的问题,一般是访问了已经释放的对象导致的,可以开启僵尸对象(Zombie Objects)来定位问题: 在Xcode的菜单: Product->Scheme->Edit Scheme->Run 右边的选项中,选中Enable Zombie Objects,就可以查看详细的错误信息: 2

黑马程序员---Objective-C基础学习---类、对象、方法相关知识笔记

------Java培训.Android培训.iOS培训..Net培训.期待与您交流! ------- 类.对象.方法相关知识笔记 Objective-C相对于C语言有了面向对象的特性,但是ObjC又没有其他面向对象语言那么多语法特性,ObjC本身对面向对象进行了精简.下面是一些相关知识笔记. 类定义 成员变量 方法和属性 self关键字 类定义 在C#.Java等其他高级语言中定义一个类是相当简单点的,直接一个关键字class加一对大括号基本就完成了,但是在ObjC中类的定义相对变化比较大.现

深入浅出安卓学习相关知识,如何从零学好移动开发

原文发表自我的个人主页,欢迎大家访问 http://purplesword.info/mobile-develop 由于近几年来互联网的飞速发展,安卓和iOS平台的大量普及推广,移动开发在当前是非常热门的一个方向. 有不少同学问我如何学习安卓,要学些什么,难不难学.之前一直没有想好应该怎么回答这个问题,只是简单的说安卓自身门槛不高,并不难学.因为我觉得准确回答一个类似这样的问题往往需要灵感.现在根据我的学习体验,做个大概的总结. 1.我为什么学安卓 我从刚开始接触安卓开发到现在也有两三年的时间了

ios开发 网络编程浅析(一)

iphone包含了很多框架和库,从底层的套接字到不同层次的封装,可以方便地给程序添加网络功能. (1)BSD套接字.最底层的套接字,这是Unix网络开发常用的API.如果从其他系统移植程序,而程序用的是BSD套接字,那么网络部分可以继续使用这些API. (2)CFNetwork framework .CFNetwork 也是比较底层的, 是对BSD套接字的一个扩展 .它是一个C语言的库,它是基于BSD套接字,提供了对网络协议的抽象.这些抽象使得用户更容易地操作套接字.处理网络的各种连接..它集成