iOS 获取通讯录里边的电话号码AddressBook
1 首先导入库 <AddressBook/AddressBook.h>
2 然后在导入#import <AddressBook/AddressBook.h>文件
3 声明 @property (nonatomic,assign) ABAddressBookRef addressBook;//电话簿
并进行初始化 self.addressBook = ABAddressBookCreateWithOptions(NULL, NULL);
4 然后进行获取通讯录的操作
ABAddressBookRequestAccessWithCompletion(self.addressBook, ^(bool granted, CFErrorRef error) { if(!granted) { NSLog(@"未获得访问权限"); } //权限状态 ABAuthorizationStatus status = ABAddressBookGetAuthorizationStatus(); if(status!=kABAuthorizationStatusAuthorized) { NSLog(@"未获得通讯录权限"); } //取得记录 CFArrayRef allPeopleCF = ABAddressBookCopyArrayOfAllPeople(self.addressBook); NSMutableArray *allPeople = (__bridge NSMutableArray *)(allPeopleCF); //过滤没用的号码 for (int i = 0; i<allPeople.count; i++) { //获得记录 ABRecordRef recordRef = (__bridge ABRecordRef)(allPeople[i]); //获得姓 NSString *firstName = (__bridge NSString *)(ABRecordCopyValue(recordRef, kABPersonFirstNameProperty)); //获得名 NSString *lastName = (__bridge NSString *)(ABRecordCopyValue(recordRef, kABPersonLastNameProperty)); //获得电话号码 ABMultiValueRef phoneNumbersRef = ABRecordCopyValue(recordRef, kABPersonPhoneProperty); //获得电话号码的长度 long count = ABMultiValueGetCount(phoneNumbersRef); //定义一个字符串用来接收电话号码 NSString *numStr = @""; if (count>0) { //将ABMultiValueRef转换成nsstring类型的 numStr = (__bridge NSString *)(ABMultiValueCopyValueAtIndex(phoneNumbersRef, 0)); //去掉86 - 还有空格 numStr = [numStr stringByReplacingOccurrencesOfString:@"+86" withString:@""]; numStr = [numStr stringByReplacingOccurrencesOfString:@"-" withString:@""]; numStr = [numStr stringByReplacingOccurrencesOfString:@" " withString:@""]; } //如果最后的是11位 就表示符合条件 if (numStr.length == 11){ // //将电话号放在可变字符串里边方便作为参数 // if(i ==allPeople.count-1){ // [self.allPhoneNum appendString:[NSString stringWithFormat:@"%@",numStr]]; // }else{ // [self.allPhoneNum appendString:[NSString stringWithFormat:@"%@,",numStr]];} // // NSLog(@"self.allPhoneNum:%@",self.allPhoneNum); //将电话号码存起来 [self.bookdatas addObject:numStr]; } } });
然后用bookDatas 在tableview中进行展示就可以了
对上述的代码,有任何疑问,可以在下方留言。
也可以给我发邮件咨询:673658917@qq.com
或者是直接加qq:673658917
转载请注明出处,谢谢合作。
睡觉舒服,那是给死人准备的,加油吧,一年后你会感谢现在的自己的。