关于通讯录联系人以及短信的处理

关于通讯录和短信的运用,需要先向工程中导入以下类库:

1.第一步:首先选择工程的Build Phases->Link Binary With Libraries,点击+添加类库

图1

2.第二步:下载pinyin.c和pinyin.h文件。下载地址


3.第三步:封装单例对象ZCAddressBook


ZCAddressBook.h文件中导入以下类库Foundation、MessageUI、AddressBookUI

图2

复制以下代码到ZCAddressBook.h中

enum{

ABHelperCanNotConncetToAddressBook,ABHelperExistSpecificContact,ABHelperNotExistSpecificContact

};typedefNSUIntegerABHelperCheckExistResultType;

@interfaceZCAddressBook :NSObject <MFMessageComposeViewControllerDelegate,ABPeoplePickerNavigationControllerDelegate>

{

}

//保存排序好的数组index

@property(nonatomic,retain)NSMutableArray*dataArray;

//数组里面保存每个获取Vcard(名片)

@property(nonatomic,retain)NSMutableArray*dataArrayDic;

#pragma mark获得单例

+ (ZCAddressBook*)shareControl;

#pragmamark添加联系人

- (BOOL)addContactName:(NSString*)name phoneNum:(NSString*)num withLabel:(NSString*)label;

- (ABHelperCheckExistResultType)existPhone:(NSString*)phoneNum;

-(NSMutableDictionary*)getPersonInfo;

-(NSArray*)sortMethod;

@property(nonatomic,assign)idtarget;

@property(nonatomic,copy)void(^MessageBlock)(int);

@property(nonatomic,copy)void(^PhoneBlock)(BOOL,NSDictionary*);

#pragma mark发送短信界面调用系统控件需要真机才能显示

-(id)initWithTarget:(id)target MessageNameArray:(NSArray*)array Message:(NSString*)str Block:(void(^)(int))a;

+(void)sendMessage:(NSString*)phoneNum;

-(id)initWithTarget:(id)target PhoneView:(void(^)(BOOL,NSDictionary*))a;

导入类库到ZCAddressBook.m中

图3

复制以下代码到ZCAddressBook.m中

staticZCAddressBook*instance;

@implementationZCAddressBook

-(id)init

{

if(self=[superinit]) {

}

returnself;

}

//单列模式

+ (ZCAddressBook*)shareControl{

@synchronized(self) {

if(!instance) {

instance= [[ZCAddressBookalloc]init];

}

}

returninstance;

}

//添加联系人(联系人名称、号码、号码备注标签)

- (BOOL)addContactName:(NSString*)name phoneNum:(NSString*)num withLabel:(NSString*)label{

//创建一条空的联系人

ABRecordRefrecord =ABPersonCreate();CFErrorReferror;

//设置联系人的名字

ABRecordSetValue(record,kABPersonFirstNameProperty, (__bridgeCFTypeRef)name, &error);

//添加联系人电话号码以及该号码对应的标签名

ABMutableMultiValueRefmulti =ABMultiValueCreateMutable(kABPersonPhoneProperty);ABMultiValueAddValueAndLabel(multi, (__bridgeCFTypeRef)num, (__bridgeCFTypeRef)label,NULL);ABRecordSetValue(record,kABPersonPhoneProperty, multi, &error);

ABAddressBookRefaddressBook =nil;

//如果为iOS6以上系统,需要等待用户确认是否允许访问通讯录。

if([[UIDevicecurrentDevice].systemVersionfloatValue] >=6.0){addressBook =ABAddressBookCreateWithOptions(NULL,NULL);

//等待同意后向下执行

dispatch_semaphore_tsema =dispatch_semaphore_create(0);ABAddressBookRequestAccessWithCompletion(addressBook, ^(boolgranted,CFErrorReferror){dispatch_semaphore_signal(sema);});

dispatch_semaphore_wait(sema,DISPATCH_TIME_FOREVER);dispatch_release(sema);

}else{

addressBook =ABAddressBookCreate();}

//将新建联系人记录添加如通讯录中

BOOLsuccess =ABAddressBookAddRecord(addressBook, record, &error);

if(!success) {

returnNO;

}else{

//如果添加记录成功,保存更新到通讯录数据库中

success =ABAddressBookSave(addressBook, &error);returnsuccess ?YES:NO;

}

}

#pragmamark指定号码是否已经存在

- (ABHelperCheckExistResultType)existPhone:(NSString*)phoneNum{

ABAddressBookRefaddressBook =nil;

if([[UIDevicecurrentDevice].systemVersionfloatValue] >=6.0){

addressBook =ABAddressBookCreateWithOptions(NULL,NULL);

//等待同意后向下执行

dispatch_semaphore_tsema =dispatch_semaphore_create(0);ABAddressBookRequestAccessWithCompletion(addressBook, ^(boolgranted,CFErrorReferror){dispatch_semaphore_signal(sema);});

dispatch_semaphore_wait(sema,DISPATCH_TIME_FOREVER);dispatch_release(sema);

}else{

addressBook =ABAddressBookCreate();

}

CFArrayRefrecords;

if(addressBook) {

//获取通讯录中全部联系人

records =ABAddressBookCopyArrayOfAllPeople(addressBook);

}else{

#ifdef DEBUGNSLog(@"can not connect to address book");

#endif

returnABHelperCanNotConncetToAddressBook;

}

//遍历全部联系人,检查是否存在指定号码

for(inti=0; i<CFArrayGetCount(records);i++) {

ABRecordRefrecord =CFArrayGetValueAtIndex(records, i);

CFTypeRefitems

=ABRecordCopyValue(record,kABPersonPhoneProperty);

CFArrayRefphoneNums

=ABMultiValueCopyArrayOfAllValues(items);

if(phoneNums) {

for(intj=0; j<CFArrayGetCount(phoneNums); j++) {

NSString*phone = (NSString*)CFArrayGetValueAtIndex(phoneNums, j);

if([phoneisEqualToString:phoneNum]) {

returnABHelperNotExistSpecificContact;

}

}

}

}CFRelease(addressBook);

}

#pragma mark获取通讯录内容

-(NSMutableDictionary*)getPersonInfo{

self.dataArray= [NSMutableArrayarrayWithCapacity:0];

self.dataArrayDic= [NSMutableArrayarrayWithCapacity:0];

//取得本地通信录名柄

ABAddressBookRefaddressBook ;

if([[UIDevicecurrentDevice].systemVersionfloatValue] >=6.0){

addressBook =ABAddressBookCreateWithOptions(NULL,NULL);

dispatch_semaphore_tsema =dispatch_semaphore_create(0);ABAddressBookRequestAccessWithCompletion(addressBook, ^(boolgranted,CFErrorReferror){dispatch_semaphore_signal(sema);});

dispatch_semaphore_wait(sema,DISPATCH_TIME_FOREVER);dispatch_release(sema);

}else{

addressBook =ABAddressBookCreate();

}

CFArrayRefresults =ABAddressBookCopyArrayOfAllPeople(addressBook);

for(inti =0;i<CFArrayGetCount(results); i++){

NSMutableDictionary*dicInfoLocal = [NSMutableDictionarydictionaryWithCapacity:0];

ABRecordRefperson =CFArrayGetValueAtIndex(results, i);

NSString*first = (NSString*)ABRecordCopyValue(person,kABPersonFirstNameProperty);

if(first==nil) {

first =@" ";

}

[dicInfoLocalsetObject:firstforKey:@"first"];

NSString*last = (NSString*)ABRecordCopyValue(person,kABPersonLastNameProperty);

if(last ==nil) {

last =@" ";

}

[dicInfoLocalsetObject:lastforKey:@"last"];

ABMultiValueReftmlphone =ABRecordCopyValue(person,kABPersonPhoneProperty);

NSString* telphone = (NSString*)ABMultiValueCopyValueAtIndex(tmlphone,0);

if(telphone ==nil) {

telphone =@" ";

}

[dicInfoLocalsetObject:telphoneforKey:@"telphone"];

CFRelease(tmlphone);

ABMultiValueRef tmpEmails = ABRecordCopyValue(person, kABPersonEmailProperty);

NSString *email = (NSString*)ABMultiValueCopyValueAtIndex(tmpEmails, 0);

[dicInfoLocal setObject:email forKey:@"email"];

CFRelease(tmpEmails);

if (email) {

email = @"";

}

[dicInfoLocal setObject:email forKey:@"email"];

if (first&&![first isEqualToString:@""]) {

[self.dataArraydic addObject:dicInfoLocal];

}

if([firstisEqualToString:@" "] ==NO|| [lastisEqualToString:@" "]) {

[self.dataArrayDicaddObject:dicInfoLocal];

}

}

CFRelease(results);//new

CFRelease(addressBook);//new

for(NSDictionary*dicinself.dataArrayDic) {

NSString* str=[dicobjectForKey:@"first"];

NSString*strFirLetter = [NSStringstringWithFormat:@"%c",pinyinFirstLetter([strcharacterAtIndex:0])];

if([strFirLetterisEqualToString:@"#"]) {

strFirLetter= [selfupperStr:[strsubstringToIndex:1]];

}

if([[indexallKeys]containsObject:strFirLetter]) {

[[indexobjectForKey:strFirLetter]addObject:dic];

}else{

NSMutableArray*tempArray=[NSMutableArrayarrayWithCapacity:0];

[tempArrayaddObject:dic];

[indexsetObject:tempArrayforKey:strFirLetter];

}

}

[self.dataArrayaddObjectsFromArray:[indexallKeys]];

returnindex;

}

-(NSString*)upperStr:(NSString*)str{

[NSLocale currentLocale]];

NSString*lowerStr = [strlowercaseStringWithLocale:[NSLocalecurrentLocale]];

returnlowerStr;

}

-(NSArray*)sortMethod

{

NSArray*array=[self.dataArraysortedArrayUsingFunction:cmpcontext:NULL];

returnarray;

}

NSIntegercmp(NSString* a,NSString* b,void* p)

{

if([acompare:b] ==1){

returnNSOrderedDescending;//(1)

}else

returnNSOrderedAscending;//(-1)

}

+(void)sendMessage:(NSString*)phoneNum{

[[UIApplicationsharedApplication]openURL:

[NSURLURLWithString:[NSStringstringWithFormat:@"sms:%@",phoneNum]]];

}

-(id)initWithTarget:(id)target MessageNameArray:(NSArray*)array Message:(NSString*)str Block:(void(^)(int))a

{

if(self=[superinit]) {

self.target=target;

self.MessageBlock=a;

[selfshowViewMessageNameArray:arrayMessage:str];

}

returnself;

}

-(void)showViewMessageNameArray:(NSArray*)array Message:(NSString*)str{

if([MFMessageComposeViewControllercanSendText]) {

MFMessageComposeViewController*messageViewController = [[MFMessageComposeViewControlleralloc]init];

messageViewController.messageComposeDelegate=self;

messageViewController.recipients= array;

messageViewController.body=str;

[self.targetpresentViewController:messageViewControlleranimated:YEScompletion:nil];

[messageViewControllerrelease];

}

}

- (void)messageComposeViewController:(MFMessageComposeViewController*)controller didFinishWithResult:(MessageComposeResult)result

{

self.MessageBlock(result);

[controllerdismissViewControllerAnimated:YEScompletion:nil];

}

-(id)initWithTarget:(id)target PhoneView:(void(^)(BOOL,NSDictionary*))a

{

if(self=[superinit]) {

self.target=target;

self.PhoneBlock=a;

ABPeoplePickerNavigationController*peoplePicker = [[ABPeoplePickerNavigationControlleralloc]init];

peoplePicker.peoplePickerDelegate=self;

[self.targetpresentViewController:peoplePickeranimated:YEScompletion:nil];

[peoplePickerrelease];

}

returnself;

}

-(BOOL)peoplePickerNavigationController:(ABPeoplePickerNavigationController*)peoplePicker shouldContinueAfterSelectingPerson:(ABRecordRef)person

{

ABMutableMultiValueRefphoneMulti =ABRecordCopyValue(person,kABPersonPhoneProperty);

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

if(firstName==nil) {

firstName =@" ";

}

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

if(lastName==nil) {

lastName =@" ";

}

NSMutableArray*phones = [NSMutableArrayarrayWithCapacity:0];

for(inti =0; i<ABMultiValueGetCount(phoneMulti); i++) {

NSString*aPhone = [(NSString*)ABMultiValueCopyValueAtIndex(phoneMulti, i)autorelease];

[phonesaddObject:aPhone];

}

NSDictionary*dic=@{@"firstName": firstName,@"lastName":lastName,@"phones":phones};

self.PhoneBlock(YES,dic);

[self.targetdismissViewControllerAnimated:YEScompletion:nil];

returnNO;

}

-(BOOL)peoplePickerNavigationController:(ABPeoplePickerNavigationController*)peoplePicker shouldContinueAfterSelectingPerson:(ABRecordRef)person property:(ABPropertyID)property identifier:(ABMultiValueIdentifier)identifier

{

self.PhoneBlock(NO,nil);

[self.targetdismissViewControllerAnimated:YEScompletion:nil];

returnNO;

}

-(void)peoplePickerNavigationControllerDidCancel:(ABPeoplePickerNavigationController*)peoplePicker

{

self.PhoneBlock(NO,nil);

[self.targetdismissViewControllerAnimated:YEScompletion:nil];

}


4.第四步:在viewcontroller.h中导入以下内容

图4

viewcontroller.m中导入ZCAddressBook.h

- (id)initWithNibName:(NSString*)nibNameOrNil bundle:(NSBundle*)nibBundleOrNil

{

self= [superinitWithNibName:nibNameOrNilbundle:nibBundleOrNil];

if(self) {

}

returnself;

}

- (void)viewDidLoad

{

[superviewDidLoad];

NSArray*array=@[@"添加联系人",@"获得Vcard",@"短信群发",@"获得指定联系人信息",@"跳出程序发短信"];

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

UIButton*button=[UIButtonbuttonWithType:UIButtonTypeCustom];

button.frame=CGRectMake(100, i*100,200,50);

[buttonsetTitle:array[i]forState:UIControlStateNormal];

[buttonsetTitleColor:[UIColorblackColor]forState:UIControlStateNormal];

button.tag=1000+i;

[buttonaddTarget:selfaction:@selector(buttonClick:)forControlEvents:UIControlEventTouchUpInside];

[self.viewaddSubview:button];

}

}

-(void)buttonClick:(UIButton*)button{

BOOLisSucceed;

NSMutableDictionary*dic;

NSArray*array;

switch(button.tag-1000) {

case0:

isSucceed=[[ZCAddressBookshareControl]addContactName:@"张三"phoneNum:@"34456789"withLabel:@"dfghjklvbn"];

NSLog(@"添加是否成功%d",isSucceed);

break;

case1:

//获得Vcard

dic= [[ZCAddressBookshareControl]getPersonInfo];

//获得序列索引

array=[[ZCAddressBookshareControl]sortMethod];

NSLog(@"Vcard%@~~~序列%@",dic,array);

break;

case2:

//拨打网络电话

[[UIApplicationsharedApplication]openURL:[NSURLURLWithString:@"tel://8008808888"]];

//发送短信,群发,可以有指定内容

[[ZCAddressBookalloc]initWithTarget:selfMessageNameArray:@[@"13811928431"]Message:@"发送消息的内容"Block:^(inttype) {

NSLog(@"发送短信后的状态");

}];

break;

case3:

//调用系统控件,选中后获得指定人信息

[[ZCAddressBookalloc]initWithTarget:selfPhoneView:^(BOOLisSucceed,NSDictionary*dic) {

NSLog(@"从系统中获得指定联系人的信息%@",dic);

}];

break;

case4:

//跳出程序进行发送短信

[ZCAddressBooksendMessage:@"13811928431"];

break;

default:

break;

}

}

好了,这样就大功告成了

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

推荐阅读更多精彩内容