ios获取手机系统通讯录

获取通讯录大体分两大种、四小种,两大种分别是基于address框架和contacts框架开发的,四小种就是这两大种分别的有UI和无UI。

但是address框架在iOS9之后就被弃用了,虽然还可以用,但是毕竟掌握新技术才是正道。下面我就把这几种的代码贴上来,供大家参考。

一、使用AddressBook.framework框架

包含框架

#import<AddressBook/AddressBook.h>

#import<AddressBookUI/AddressBookUI.h>

集成代理 ABPeoplePickerNavigationControllerDelegate

1、使用UI界面

- (IBAction)addressYes:(id)sender {

ABPeoplePickerNavigationController * peoplePickerNav = [ABPeoplePickerNavigationController new];

peoplePickerNav.peoplePickerDelegate=self;

[selfpresentViewController:peoplePickerNav animated:YEScompletion:nil];

}

//===========address//- (void)peoplePickerNavigationController:(ABPeoplePickerNavigationController*)peoplePicker didSelectPerson:(ABRecordRef)person {////    NSLog(@"选中了person,%@",person);//}

-(void)peoplePickerNavigationController(ABPeoplePickerNavigationController*)peoplePicker didSelectPerson:(ABRecordRef)person property:(ABPropertyID)property identifier:(ABMultiValueIdentifier)identifier{

NSLog(@"选中了属性,property:%d,identifier:%d",property,identifier);

}

2、界面无UI

// address框架无UI

- (IBAction)addressNo:(id)sender {

//这个变量用于记录授权是否成功,即用户是否允许我们访问通讯录

int__block tip =0;

//声明一个通讯簿的引用

ABAddressBookRef addBook =nil;

//创建通讯簿的引用

addBook = ABAddressBookCreateWithOptions(NULL,NULL);

//创建一个出事信号量为0的信号

dispatch_semaphore_t sema = dispatch_semaphore_create(0);

//申请访问权限

ABAddressBookRequestAccessWithCompletion(addBook, ^(boolgreanted, CFErrorRef error)        {

//greanted为YES是表示用户允许,否则为不允许

if(!greanted) {

tip =1;

}

//发送一次信号

dispatch_semaphore_signal(sema);

});

//等待信号触发

dispatch_semaphore_wait(sema, DISPATCH_TIME_FOREVER);if(tip) {

//做一个友好的提示

UIAlertView * alart = [[UIAlertView alloc]initWithTitle:@"温馨提示"message:@"请您设置允许APP访问您的通讯录\nSettings>General>Privacy"delegate:selfcancelButtonTitle:@"确定"otherButtonTitles:nil,nil];

[alart show];return;

}

//获取所有联系人的数组

CFArrayRef allLinkPeople = ABAddressBookCopyArrayOfAllPeople(addBook);

//获取联系人总数

CFIndex number = ABAddressBookGetPersonCount(addBook);

//进行遍历

for(inti =0; i < number; i++) {

//获取联系人对象的引用

ABRecordRef  people = CFArrayGetValueAtIndex(allLinkPeople, i);

//获取当前联系人名字

NSString* firstName = (__bridgeNSString*)(ABRecordCopyValue(people, kABPersonFirstNameProperty));

//获取当前联系人姓氏

NSString* lastName=(__bridgeNSString*)(ABRecordCopyValue(people, kABPersonLastNameProperty));

//获取当前联系人的名字拼音

NSString* firstNamePhoneic=(__bridgeNSString*)(ABRecordCopyValue(people, kABPersonFirstNamePhoneticProperty));

//获取当前联系人的备注

NSString* notes = (__bridgeNSString*)(ABRecordCopyValue(people, kABPersonNoteProperty));

//获取当前联系人的电话 数组

NSMutableArray* phoneArr = [[NSMutableArrayalloc]init];

ABMultiValueRef phones= ABRecordCopyValue(people, kABPersonPhoneProperty);for(NSIntegerj =0; j < ABMultiValueGetCount(phones); j++) {

[phoneArr addObject:(__bridgeNSString*)(ABMultiValueCopyValueAtIndex(phones, j))];

}

//获取当前联系人头像图片

NSData * userImage=(__bridge NSData*)(ABPersonCopyImageData(people));NSLog(@"firstName:%@,lastName:%@,firstNamePhoneic:%@,notes:%@,phoneArr:%@,userImage:%@",firstName,lastName,firstNamePhoneic,notes,phoneArr,userImage);

}

}

二、Contacts框架

包含框架

#import<Contacts/Contacts.h>

#import<ContactsUI/ContactsUI.h>

集成代理 CNContactPickerDelegate

代码如下  TKAddressBook *addressBook为数据模型,self.listContacts为承载模型的可变数组。

[self.listContacts removeAllObjects];

CNContactStore *store = [[CNContactStore alloc] init];

NSArray *typeArray = @[CNContactGivenNameKey,CNContactFamilyNameKey,CNContactPhoneNumbersKey,CNContactOrganizationNameKey,CNContactEmailAddressesKey,CNContactPostalAddressesKey,CNContactInstantMessageAddressesKey];

CNContactFetchRequest *request = [[CNContactFetchRequest alloc] initWithKeysToFetch:typeArray];

//遍历所有的联系人

NSMutableDictionary *addressBookDict = [NSMutableDictionary dictionary];

[store enumerateContactsWithFetchRequest:request error:nil usingBlock:^(CNContact * _Nonnull contact, BOOL * _Nonnull stop) {

NSArray *phones = contact.phoneNumbers;

for (int i = 0; i < phones.count; i++) {

TKAddressBook *addressBook = [[TKAddressBook alloc] init];

NSString *firstName = contact.givenName;

NSString *lastName = contact.familyName;

if ([Tool isBlankString:firstName]) {

firstName = @"";

}

if ([Tool isBlankString:lastName]) {

lastName = @"";

}

//姓名

addressBook.name = [NSString stringWithFormat:@"%@%@",lastName,firstName];

CNLabeledValue *phone = phones[i];

CNPhoneNumber *phoneNum = phone.value;

NSString *num = phoneNum.stringValue;

num = [num stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];

num = [num stringByReplacingOccurrencesOfString:@"\r" withString:@""];

num = [num stringByReplacingOccurrencesOfString:@"\n" withString:@""];

num = [num stringByReplacingOccurrencesOfString:@"\t" withString:@""];

num = [num stringByReplacingOccurrencesOfString:@"+86" withString:@""];

num = [num stringByReplacingOccurrencesOfString:@"-" withString:@""];

num = [num stringByReplacingOccurrencesOfString:@" " withString:@""];

addressBook.mobileNo = [NSString stringWithFormat:@"%@",num];

//公司

addressBook.company = contact.organizationName;

NSMutableString *str = [[NSMutableString alloc]init];;

//电子邮箱

for (int i = 0; i < contact.emailAddresses.count; i++) {

CNLabeledValue *email = contact.emailAddresses[i];

if (i == 0) {

[str appendString:[NSString stringWithFormat:@"%@",email.value]];

}else if(i > 0 &&i < contact.emailAddresses.count - 1){

[str appendString:[NSString stringWithFormat:@",%@",email.value]];

}

}

addressBook.emailArr = str;

//地址

NSString *addressStr = [[NSString alloc]init];

for (int i = 0; i < contact.postalAddresses.count; i++) {

CNLabeledValue *address = contact.postalAddresses[0];

CNPostalAddress *model = address.value;

addressStr = [NSString stringWithFormat:@"%@%@%@%@%@",model.country,model.state,model.city,model.subLocality,model.street];

}

addressStr = [addressStr stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]]; //去除掉首尾的空白字符和换行字符

addressStr = [addressStr stringByReplacingOccurrencesOfString:@"\r" withString:@""];

addressStr = [addressStr stringByReplacingOccurrencesOfString:@"\n" withString:@""];

addressStr = [addressStr stringByReplacingOccurrencesOfString:@"\t" withString:@""];

addressBook.address = addressStr;

[self.listContacts addObject:addressBook];

NSString *firstLetterString = [self getFirstLetterFromString:addressBook.name];

if (addressBookDict[firstLetterString]){

[addressBookDict[firstLetterString] addObject:addressBook];

}else{

//创建新发可变数组存储该首字母对应的联系人模型

NSMutableArray *arrGroupNames = [NSMutableArray arrayWithObject:addressBook];

//将首字母-姓名数组作为key-value加入到字典中

[addressBookDict setObject:arrGroupNames forKey:firstLetterString];

}

self.tableDic = addressBookDict;

}

}];

TKAddressBook *addressBook模型参数如下

@property (strong, nonatomic) NSString *name;

@property (strong, nonatomic) NSString *emailArr;

@property (strong, nonatomic) NSString *mobileNo;

@property (strong, nonatomic) NSString *company;    //公司

@property (strong, nonatomic) NSString *address;

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 159,219评论 4 362
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,363评论 1 293
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 108,933评论 0 243
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 44,020评论 0 206
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,400评论 3 287
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,640评论 1 219
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,896评论 2 313
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,597评论 0 199
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,327评论 1 244
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,581评论 2 246
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,072评论 1 261
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,399评论 2 253
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,054评论 3 236
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,083评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,849评论 0 195
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,672评论 2 274
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,585评论 2 270

推荐阅读更多精彩内容