1.需要引入AddressBook.framework框架
2.iPhone通讯录的增加联系人的操作,代码如下(放到项目中可直接运行):
// 初始化一个ABAddressBookRef对象,使用完之后需要进行释放,
// 这里使用CFRelease进行释放
// 相当于通讯录的一个引用
ABAddressBookRef addressBook = ABAddressBookCreate();
// 新建一个联系人
// ABRecordRef是一个属性的集合,相当于通讯录中联系人的对象
// 联系人对象的属性分为两种:
// 只拥有唯一值的属性和多值的属性。
// 唯一值的属性包括:姓氏、名字、生日等。
// 多值的属性包括:电话号码、邮箱等。
ABRecordRef person = ABPersonCreate();
NSString *firstName = @"四";
NSString *lastName = @"李";
NSDate *birthday = [NSDate date];
// 电话号码数组
NSArray *phones = [NSArray arrayWithObjects:@"123",@"456", nil];
// 电话号码对应的名称
NSArray *labels = [NSArray arrayWithObjects:@"iphone",@"home", nil];
// 保存到联系人对象中,每个属性都对应一个宏,例如:kABPersonFirstNameProperty
// 设置firstName属性
ABRecordSetValue(person, kABPersonFirstNameProperty, (CFStringRef)firstName, NULL);
// 设置lastName属性
ABRecordSetValue(person, kABPersonLastNameProperty, (CFStringRef) lastName, NULL);
// 设置birthday属性
ABRecordSetValue(person, kABPersonBirthdayProperty, (CFDateRef)birthday, NULL);
// ABMultiValueRef类似是Objective-C中的NSMutableDictionary
ABMultiValueRef mv = ABMultiValueCreateMutable(kABMultiStringPropertyType);
// 添加电话号码与其对应的名称内容
for (int i = 0; i < [phones count]; i ++) {
ABMultiValueIdentifier mi = ABMultiValueAddValueAndLabel(mv, (CFStringRef)[phones objectAtIndex:i], (CFStringRef)[labels objectAtIndex:i], &mi);
}
// 设置phone属性
ABRecordSetValue(person, kABPersonPhoneProperty, mv, NULL);
// 释放该数组
if (mv) {
CFRelease(mv);
}
// 将新建的联系人添加到通讯录中
ABAddressBookAddRecord(addressBook, person, NULL);
// 保存通讯录数据
ABAddressBookSave(addressBook, NULL);
// 释放通讯录对象的引用
if (addressBook) {
CFRelease(addressBook);
}
------------------------------------------------------------------------------------------------
3.删除联系人的操作,代码如下(放到项目中可直接运行):
// 初始化并创建通讯录对象,记得释放内存
ABAddressBookRef addressBook = ABAddressBookCreate();
// 获取通讯录中所有的联系人
NSArray *array = (NSArray *)ABAddressBookCopyArrayOfAllPeople(addressBook);
// 遍历所有的联系人并删除(这里只删除姓名为张三的)
for (id obj in array) {
ABRecordRef people = (ABRecordRef)obj;
NSString *firstName = (NSString *)ABRecordCopyValue(people, kABPersonFirstNameProperty);
NSString *lastName = (NSString *)ABRecordCopyValue(people, kABPersonLastNameProperty);
if ([firstName isEqualToString:@"三"] && [lastName isEqualToString:@"张"]) {
ABAddressBookRemoveRecord(addressBook, people, NULL);
}
}
// 保存修改的通讯录对象
ABAddressBookSave(addressBook, NULL);
// 释放通讯录对象的内存
if (addressBook) {
CFRelease(addressBook);
}
-------------------------------------------------------------------------------------------------
4.修改联系人的操作,代码如下(由于项目中使用到了修改联系人的操作,所以将方法直接复制过来了):
// 根据姓氏、名字以及手机号码修改联系人的昵称和生日
+ (void) updateAddressBookPersonWithFirstName:(NSString *)firstName
lastName:(NSString *)lastName
mobile:(NSString *)mobile
nickname:(NSString *)nickname
birthday:(NSDate *)birthday {
// 初始化并创建通讯录对象,记得释放内存
ABAddressBookRef addressBook = ABAddressBookCreate();
// 获取通讯录中所有的联系人
NSArray *array = (NSArray *)ABAddressBookCopyArrayOfAllPeople(addressBook);
// 遍历所有的联系人并修改指定的联系人
for (id obj in array) {
ABRecordRef people = (ABRecordRef)obj;
NSString *fn = (NSString *)ABRecordCopyValue(people, kABPersonFirstNameProperty);
NSString *ln = (NSString *)ABRecordCopyValue(people, kABPersonLastNameProperty);
ABMultiValueRef mv = ABRecordCopyValue(people, kABPersonPhoneProperty);
NSArray *phones = (NSArray *)ABMultiValueCopyArrayOfAllValues(mv);
// firstName同时为空或者firstName相等
BOOL ff = ([fn length] == 0 && [firstName length] == 0) || ([fn isEqualToString:firstName]);
// lastName同时为空或者lastName相等
BOOL lf = ([ln length] == 0 && [lastName length] == 0) || ([ln isEqualToString:lastName]);
// 由于获得到的电话号码不符合标准,所以要先将其格式化再比较是否存在
BOOL is = NO;
for (NSString *p in phones) {
// 红色代码处,我添加了一个类别(给NSString扩展了一个方法),该类别的这个方法主要是用于将电话号码中的"("、")"、" "、"-"过滤掉
if ([[p iPhoneStandardFormat] isEqualToString:mobile]) {
is = YES;
break;
}
}
// firstName、lastName、mobile 同时存在进行修改
if (ff && lf && is) {
if ([nickname length] > 0) {
ABRecordSetValue(people, kABPersonNicknameProperty, (CFStringRef)nickname, NULL);
}
if (birthday != nil) {
ABRecordSetValue(people, kABPersonBirthdayProperty, (CFDataRef)birthday, NULL);
}
}
}
// 保存修改的通讯录对象
ABAddressBookSave(addressBook, NULL);
// 释放通讯录对象的内存
if (addressBook) {
CFRelease(addressBook);
}
}
这几个是AddressBook 中的内容
ABRecordRef这个是某一条通讯录记录
ABMultiValueRef这个是通讯录中某一个可能有多个字段数值的记录
ABAddressBookRef 这货就是某个通讯录了
ABRecordID这个是记录的id, int类型
至于区别。。。这几个根本就不是一样的东西,谈不上区别
建议楼主去看下addressbook的相关官方例子ABUIGroups等等
github.com上面还有一个特棒的项目RHAddressBook
https://github.com/heardrwt/RHAddressBook
Include RHAddressBook in your iOS project.
#import <RHAddressBook/AddressBook.h>
Getting an instance of the addressbook.
RHAddressBook *ab = [[[RHAddressBook alloc] init] autorelease];
Support for iOS6+ authorization
//query current status, pre iOS6 always returns Authorized
if ([RHAddressBook authorizationStatus] == RHAuthorizationStatusNotDetermined){
//request authorization
[ab requestAuthorizationWithCompletion:^(bool granted, NSError *error) {
[abViewController setAddressBook:ab];
}];
}
Registering for addressbook changes
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(addressBookChanged:) name:RHAddressBookExternalChangeNotification object:nil];
Getting sources.
NSArray *sources = [ab sources];
RHSource *defaultSource = [ab defaultSource];
Getting a list of groups.
NSArray *groups = [ab groups];
long numberOfGroups = [ab numberOfGroups];
NSArray *groupsInSource = [ab groupsInSource:defaultSource];
RHGroup *lastGroup = [groups lastObject];
Getting a list of people.
NSArray *allPeople = [ab people];
long numberOfPeople = [ab numberOfPeople];
NSArray *allPeopleSorted = [ab peopleOrderedByUsersPreference];
NSArray *allFreds = [ab peopleWithName:@"Fred"];
NSArray *allFredsInLastGroup = [lastGroup peopleWithName:@"Fred"];
RHPerson *person = [allPeople lastObject];
Getting basic properties on on a person.
NSString *department = [person department];
UIImage *thumbnail = [person thumbnail];
BOOL isCompany = [person isOrganization];
Setting basic properties on a person.
person.name = @"Freddie";
[person setImage:[UIImage imageNames:@"hahaha.jpg"]];
person.kind = kABPersonKindOrganization;
[person save];
Getting MultiValue properties on a person.
RHMultiDictionaryValue *addressesMultiValue = [person addresses];
NSString *firstAddressLabel = [RHPerson localizedLabel:[addressesMultiValue labelAtIndex]]; //eg Home
NSDictionary *firstAddress = [addressesMultiValue valueAtIndex:0];
Setting MultiValue properties on a person.
RHMultiStringValue *phoneMultiValue = [person phoneNumbers];
RHMutableMultiStringValue *mutablePhoneMultiValue = [[phoneMultiValue mutableCopy] autorelease];
if (! mutablePhoneMultiValue) mutablePhoneMultiValue = [[[RHMutableMultiStringValue alloc] initWithType:kABMultiStringPropertyType] autorelease];
//RHPersonPhoneIPhoneLabel casts kABPersonPhoneIPhoneLabel to the correct toll free bridged type, see RHPersonLabels.h
mutablePhoneMultiValue addValue:@"+14086655555" withLabel:RHPersonPhoneIPhoneLabel];
person.phonenumbers = mutablePhoneMultiValue;
[person save];
Creating a new person.
RHPerson *newPerson = [[ab newPersonInDefaultSource] autorelease]; //added to ab
RHPerson *newPerson2 = [[[RHPerson newPersonInSource:[ab defaultSource]] autorelease]; //not added to ab
[ab addPerson:newPerson2];
NSError* error = nil;
if (![ab save:&error]) NSLog(@"error saving: %@", error);
Getting an RHPerson object for an ABRecordRef for editing. (note: RHPerson might not be associated with the same addressbook as the original ABRecordRef)
ABRecordRef personRef = ...;
RHPerson *person = [ab personForRecordRef:personRef];
if(person){
person.firstName = @"Paul";
person.lastName = @"Frank";
[person save];
}
Presenting / editing an RHPerson instance in a ABPersonViewController.
ABPersonViewController *personViewController = [[[ABPersonViewController alloc] init] autorelease];
//setup (tell the view controller to use our underlying address book instance, so our person object is directly updated on our behalf)
[person.addressBook performAddressBookAction:^(ABAddressBookRef addressBookRef) {
personViewController.addressBook =addressBookRef;
} waitUntilDone:YES];
personViewController.displayedPerson = person.recordRef;
personViewController.allowsEditing = YES;
[self.navigationController pushViewController:personViewController animated:YES];
Background geocoding
if ([RHAddressBook isGeocodingSupported){
[RHAddressBook setPreemptiveGeocodingEnabled:YES]; //class method
}
float progress = [_addressBook preemptiveGeocodingProgress]; // 0.0f - 1.0f
Geocoding results for a person.
CLLocation *location = [person locationForAddressID:0];
CLPlacemark *placemark = [person placemarkForAddressID:0];
Finding people within distance of a location.
NSArray *inRangePeople = [ab peopleWithinDistance:5000 ofLocation:location];
NSLog(@"people:%@", inRangePeople);
Saving. (all of the below are equivalent)
BOOL changes = [ab hasUnsavedChanges];
BOOL result = [ab save];
BOOL result =[source save];
BOOL result =[group save];
BOOL result =[person save];
Reverting changes on objects. (reverts the entire addressbook instance, not just the object revert is called on.)
[ab revert];
[source revert];
[group revert];
[person revert];
Remember, save often in order to avoid painful save conflicts.
具体的例子可以看附件: