通讯录获取和带号码分区排序
来源:互联网 发布:西部数码域名证书查询 编辑:程序博客网 时间:2024/09/21 11:13
结合大牛的第三方库 修改了一下 实现了获取通讯录 并实现带号码排序的功能
先创建model
#import <Foundation/Foundation.h>
@interface TKAddressBook : NSObject {
NSInteger sectionNumber;
NSInteger recordID;
NSString *name;
NSString *email;
NSString *tel;
}
@property NSInteger sectionNumber;
@property NSInteger recordID;
@property (nonatomic, retain) NSString *name;
@property (nonatomic, retain) NSString *email;
@property (nonatomic, retain) NSString *tel;
@end
#import "TKAddressBook.h"
@implementation TKAddressBook
@synthesize name, email, tel, recordID, sectionNumber;
@end
控制器
#import "LinkmanViewController.h"
#import <AddressBookUI/AddressBookUI.h>
#import <AddressBook/AddressBook.h>
#import "TKAddressBook.h"
#import "TKAddressViewCell.h"
#import "ChineseString.h"
@interface LinkmanViewController () <UITableViewDataSource,UITableViewDelegate>
@property (nonatomic,strong) TKAddressViewCell *cell;
@property (nonatomic,strong) NSMutableArray *addressBookTemp;
@property(nonatomic,retain)NSMutableArray *indexArray;
//设置每个section下的cell内容
@property(nonatomic,retain)NSMutableArray *LetterResultArr;
@end
@implementation LinkmanViewController
@synthesize indexArray;
@synthesize LetterResultArr;
- (void)viewDidLoad {
[super viewDidLoad];
self.select=NO;
_addressBookTemp=[[NSMutableArray alloc] init];
self.TelArrary=[[NSMutableArray alloc] init];
[self Getback];
[self getAddressBook];
[self setUI];
}
-(void)setUI{
_tableView=[[UITableView alloc] initWithFrame:CGRectMake(0, 40, kScreenSize.width, kScreenSize.height-49-60-40) style:UITableViewStyleGrouped];
[_tableView registerNib:[UINib nibWithNibName:@"TKAddressViewCell" bundle:nil] forCellReuseIdentifier:@"TKAddressViewCell"];
_tableView.delegate=self;
_tableView.dataSource=self;
_tableView.bounces=NO;
[_tableView setEditing:YES];
[self.view addSubview:_tableView];
}
//查找联系人
-(void)getAddressBook{
//新建一个通讯录类
ABAddressBookRef addressBooks = nil;
if ([[UIDevice currentDevice].systemVersion floatValue] >= 6.0)
{
addressBooks = ABAddressBookCreateWithOptions(NULL, NULL);
//获取通讯录权限
dispatch_semaphore_t sema = dispatch_semaphore_create(0);
ABAddressBookRequestAccessWithCompletion(addressBooks, ^(bool granted, CFErrorRef error){dispatch_semaphore_signal(sema);});
dispatch_semaphore_wait(sema, DISPATCH_TIME_FOREVER);
}
else
{
addressBooks = ABAddressBookCreate();
}
//获取通讯录中的所有人
CFArrayRef allPeople = ABAddressBookCopyArrayOfAllPeople(addressBooks);
//通讯录中人数
CFIndex nPeople = ABAddressBookGetPersonCount(addressBooks);
//循环,获取每个人的个人信息
for (NSInteger i = 0; i < nPeople; i++)
{
//新建一个addressBook model类
TKAddressBook *addressBook = [[TKAddressBook alloc] init];
//获取个人
ABRecordRef person = CFArrayGetValueAtIndex(allPeople, i);
//获取个人名字
CFTypeRef abName = ABRecordCopyValue(person, kABPersonFirstNameProperty);
CFTypeRef abLastName = ABRecordCopyValue(person, kABPersonLastNameProperty);
CFStringRef abFullName = ABRecordCopyCompositeName(person);
NSString *nameString = (__bridge NSString *)abName;
NSString *lastNameString = (__bridge NSString *)abLastName;
if ((__bridge id)abFullName != nil) {
nameString = (__bridge NSString *)abFullName;
} else {
if ((__bridge id)abLastName != nil)
{
nameString = [NSString stringWithFormat:@"%@ %@", nameString, lastNameString];
}
}
if (nameString==nil) {
//如果名字为空 删除此项
continue;
}
addressBook.name = nameString;
addressBook.recordID = (int)ABRecordGetRecordID(person);;
ABPropertyID multiProperties[] = {
kABPersonPhoneProperty,
kABPersonEmailProperty
};
NSInteger multiPropertiesTotal = sizeof(multiProperties) / sizeof(ABPropertyID);
for (NSInteger j = 0; j < multiPropertiesTotal; j++) {
ABPropertyID property = multiProperties[j];
ABMultiValueRef valuesRef = ABRecordCopyValue(person, property);
NSInteger valuesCount = 0;
if (valuesRef != nil) valuesCount = ABMultiValueGetCount(valuesRef);
if (valuesCount == 0) {
CFRelease(valuesRef);
continue;
}
//获取电话号码和email
for (NSInteger k = 0; k < valuesCount; k++) {
CFTypeRef value = ABMultiValueCopyValueAtIndex(valuesRef, k);
switch (j) {
case 0: {// Phone number
addressBook.tel = (__bridge NSString*)value;
break;
}
case 1: {// Email
addressBook.email = (__bridge NSString*)value;
break;
}
}
CFRelease(value);
}
CFRelease(valuesRef);
}
//将个人信息添加到数组中,循环完成后addressBookTemp中包含所有联系人的信息
[_addressBookTemp addObject:addressBook];
if (abName) CFRelease(abName);
if (abLastName) CFRelease(abLastName);
if (abFullName) CFRelease(abFullName);
}
self.indexArray = [ChineseString IndexArray:_addressBookTemp];
self.LetterResultArr = [ChineseString LetterSortArray:_addressBookTemp];
}
#pragma mark - delegate
#pragma mark -Section的Header的值
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
NSString *key = [indexArray objectAtIndex:section];
return key;
}
#pragma mark - Section header view
-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
UILabel *lab = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 320, 20)];
lab.backgroundColor = kUIColorFromRGB(0x90cbf1);
lab.text = [NSString stringWithFormat:@" %@",[indexArray objectAtIndex:section]];
lab.textColor = [UIColor whiteColor];
return lab;
}
#pragma mark -
#pragma mark Table View Data Source Methods
#pragma mark -设置右方表格的索引数组
-(NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView
{
return indexArray;
}
#pragma mark -
- (NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index
{
NSLog(@"title===%@",title);
return index;
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
return [self.LetterResultArr count];
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
return [[self.LetterResultArr objectAtIndex:section] count];
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
return 50;
}
-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
return 1;
}
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
return 20;
}
- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath {
return UITableViewCellEditingStyleDelete |
UITableViewCellEditingStyleInsert;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
TKAddressBook *book = [[self.LetterResultArr objectAtIndex:indexPath.section]objectAtIndex:indexPath.row];
if (self.select==YES) {
[_tableView selectRowAtIndexPath:indexPath animated:YES scrollPosition:UITableViewScrollPositionNone];
[self.TelArrary addObject:book.tel];
}else{
[_tableView deselectRowAtIndexPath:indexPath animated:NO];
[_TelArrary removeAllObjects];
}
static NSString *cellID = @"cellID";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellID];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:cellID] ;
}
cell.textLabel.text=book.name;
cell.detailTextLabel.text=book.tel;
return cell;
}
#pragma mark - Select内容为数组相应索引的值
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
if (self.tableView.isEditing) {
TKAddressBook *book = [_addressBookTemp objectAtIndex:indexPath.row];
[self.TelArrary addObject:book.tel];
}
}
-(void)tableView:(UITableView *)tableView didDeselectRowAtIndexPath:(NSIndexPath *)indexPath{
if (self.tableView.isEditing) {
TKAddressBook *book = [_addressBookTemp objectAtIndex:indexPath.row];
[self.TelArrary removeObject:book.tel];
}
}
-(void)OKButton:(UIButton *)button{
[self.BackView removeFromSuperview];
}
@end
#import <Foundation/Foundation.h>
#import "pinyin.h"
@interface ChineseString : NSObject
@property(retain,nonatomic)NSString *string;
@property(retain,nonatomic)NSString *pinYin;
//----- 返回tableview右方indexArray
+(NSMutableArray*)IndexArray:(NSArray*)stringArr;
//----- 返回联系人
+(NSMutableArray*)LetterSortArray:(NSArray*)stringArr;
///----------------------
//返回一组字母排序数组(中英混排)
+(NSMutableArray*)SortArray:(NSArray*)stringArr;
@end
#import "ChineseString.h"
#import "TKAddressBook.h"@implementation ChineseString
@synthesize string;
@synthesize pinYin;
#pragma mark - 返回tableview右方 indexArray
+(NSMutableArray*)IndexArray:(NSArray*)stringArr
{
NSMutableArray *tempArray = [self ReturnSortChineseArrar:stringArr];
NSMutableArray *A_Result=[NSMutableArray array];
NSString *tempString ;
for (NSString* object in tempArray)
{
NSString *pinyin = [((ChineseString*)object).pinYin substringToIndex:1];
//不同
if(![tempString isEqualToString:pinyin])
{
// NSLog(@"IndexArray----->%@",pinyin);
[A_Result addObject:pinyin];
tempString = pinyin;
}
}
return A_Result;
}
#pragma mark - 返回联系人
+(NSMutableArray*)LetterSortArray:(NSArray*)stringArr
{
NSMutableArray *tempArray = [self ReturnSortChineseArrar:stringArr];
NSMutableArray *ResultArray=[[NSMutableArray alloc] init];
for (int k=0; k<tempArray.count; k++) {
for (int j=0; j<tempArray.count; j++) {
TKAddressBook *book = [stringArr objectAtIndex:j];
NSString *name=[book.name stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
NSString *Name =[ChineseString RemoveSpecialCharacter:name];
if ([Name isEqualToString:((ChineseString*)[tempArray objectAtIndex:k]).string]) {
[ResultArray addObject:stringArr[j]];
}
}
}
NSMutableArray *LetterResult=[NSMutableArray array];
NSMutableArray *item = [NSMutableArray array];
NSString *tempString ;
//拼音分组
for (int i=0; i<tempArray.count; i++) {
NSString *pinyin = [((ChineseString*)tempArray[i]).pinYin substringToIndex:1];
// NSString *string = ((ChineseString*)tempArray[i]).string;
//不同
if(![tempString isEqualToString:pinyin])
{
//分组
item = [NSMutableArray array];
[item addObject:ResultArray[i]];
[LetterResult addObject:item];
//遍历
tempString = pinyin;
}else//相同
{
[item addObject:ResultArray[i]];
}
}
return LetterResult;
}
//过滤指定字符串 里面的指定字符根据自己的需要添加
+(NSString*)RemoveSpecialCharacter: (NSString *)str {
NSRange urgentRange = [str rangeOfCharacterFromSet: [NSCharacterSet characterSetWithCharactersInString: @",.?、 ~¥#&<>《》()[]{}【】^@/£¤|§¨「」『』¢¬ ̄~@#&*()——+|《》$_€"]];
if (urgentRange.location != NSNotFound)
{
return [self RemoveSpecialCharacter:[str stringByReplacingCharactersInRange:urgentRange withString:@""]];
}
return str;
}
///////////////////
//
//返回排序好的字符拼音
//
///////////////////
+(NSMutableArray*)ReturnSortChineseArrar:(NSArray*)stringArr
{
//获取字符串中文字的拼音首字母并与字符串共同存放
NSMutableArray *chineseStringsArray=[NSMutableArray array];
for(int i=0;i<[stringArr count];i++)
{
TKAddressBook *book = [stringArr objectAtIndex:i];
ChineseString *chineseString=[[ChineseString alloc]init];
if (book.name==nil) {
continue ;
}
chineseString.string=[NSString stringWithString:book.name];
if(chineseString.string==nil){
chineseString.string=@"";
}
//去除两端空格和回车
chineseString.string = [chineseString.string stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
//此方法存在一些问题 有些字符过滤不了
//NSCharacterSet *set = [NSCharacterSet characterSetWithCharactersInString:@"@/:;()¥「」"、[]{}#%-*+=_\\|~<>$€^•'@#$%^&*()_+'\""];
//chineseString.string = [chineseString.string stringByTrimmingCharactersInSet:set];
//这里我自己写了一个递归过滤指定字符串 RemoveSpecialCharacter
chineseString.string =[ChineseString RemoveSpecialCharacter:chineseString.string];
// NSLog(@"string====%@",chineseString.string);
//判断首字符是否为字母
NSString *regex = @"[A-Za-z]+";
NSPredicate*predicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",regex];
if ([predicate evaluateWithObject:chineseString.string])
{
//首字母大写
chineseString.pinYin = [chineseString.string capitalizedString] ;
}else{
if(![chineseString.string isEqualToString:@""]){
NSString *pinYinResult=[NSString string];
for(int j=0;j<chineseString.string.length;j++){
NSString *singlePinyinLetter=[[NSString stringWithFormat:@"%c",pinyinFirstLetter([chineseString.string characterAtIndex:j])]uppercaseString];
pinYinResult=[pinYinResult stringByAppendingString:singlePinyinLetter];
}
chineseString.pinYin=pinYinResult;
}else{
chineseString.pinYin=@"";
}
}
[chineseStringsArray addObject:chineseString];
}
//按照拼音首字母对这些Strings进行排序
NSArray *sortDescriptors = [NSArray arrayWithObject:[NSSortDescriptor sortDescriptorWithKey:@"pinYin" ascending:YES]];
[chineseStringsArray sortUsingDescriptors:sortDescriptors];
return chineseStringsArray;
}
//
//for(int i=0;i<[chineseStringsArray count];i++){
// // NSLog(@"chineseStringsArray====%@",((ChineseString*)[chineseStringsArray objectAtIndex:i]).pinYin);
//}
//// NSLog(@"-----------------------------");
#pragma mark - 返回一组字母排序数组
+(NSMutableArray*)SortArray:(NSArray*)stringArr
{
NSMutableArray *tempArray = [self ReturnSortChineseArrar:stringArr];
//把排序好的内容从ChineseString类中提取出来
NSMutableArray *result=[NSMutableArray array];
for(int i=0;i<[stringArr count];i++){
[result addObject:((ChineseString*)[tempArray objectAtIndex:i]).string];
NSLog(@"SortArray----->%@",((ChineseString*)[tempArray objectAtIndex:i]).string);
}
return result;
}
@end
最后添加 pinyin.c 和pinyin.h 库 可以在网上查找
- 通讯录获取和带号码分区排序
- [自学Android之旅] 获取通讯录的联系人 姓名和号码
- android调用系统通讯录,并返回联系人号码和称呼
- Android调用系统通讯录,并返回联系人号码和称呼
- Android通讯录添加号码
- Android 获取来电号码和去电号码
- iphone获取本机电话号码 iPhone获取通讯录里电话号码
- 获取cup和硬盘的id号码
- 演示ContentProvider使用--获取通讯录所有联系人号码、email的例子
- Android通讯录开发之获取运营商号码段(移动、联通、电信)
- Android通讯录开发之获取运营商号码段(移动、联通、电信)
- IOS通讯录选取某个号码
- 获取腾讯企业邮箱通讯录python脚本(带登录功能)
- 根据联系人号码获取sort_key以实现按字母排序
- Android 获取imei号码,获取手机型号和系统版本号
- Android 获取imei号码,获取手机型号和系统版本号
- Android 获取imei号码,获取手机型号和系统版本号
- Android获取手机短信和通话记录及通讯录
- 远程通信的几种选择(RPC,Webservice,RMI,JMS的区别)
- Ant自动编译打包&发布 android项目
- JVM内存分析工具介绍
- php define
- 使用JQuery上传图片 实现预览
- 通讯录获取和带号码分区排序
- Hibernate get 和load的区别
- Window快捷键简介
- Android M(6.0) 中删除Apache HTTP Client的解决方案
- 创建可以拖动的按钮
- soapUI 环境管理
- 使用MyBatis和logBack时在日志中输出sql
- hibernate select语句
- android反编译Apk