关于通讯录和短信的运用,需要先向工程中导入以下类库:
1.第一步:首先选择工程的Build Phases->Link Binary With Libraries,点击+添加类库
2.第二步:下载pinyin.c和pinyin.h文件。下载地址
3.第三步:封装单例对象ZCAddressBook
ZCAddressBook.h文件中导入以下类库Foundation、MessageUI、AddressBookUI
复制以下代码到ZCAddressBook.h中
enum{
ABHelperCanNotConncetToAddressBook,ABHelperExistSpecificContact,ABHelperNotExistSpecificContact
};typedefNSUIntegerABHelperCheckExistResultType;
@interfaceZCAddressBook :NSObject
{
}
//保存排序好的数组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中
复制以下代码到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
ABRecordRefrecord =CFArrayGetValueAtIndex(records, i);
CFTypeRefitems
=ABRecordCopyValue(record,kABPersonPhoneProperty);
CFArrayRefphoneNums
=ABMultiValueCopyArrayOfAllValues(items);
if(phoneNums) {
for(intj=0; 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
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
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中导入以下内容
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;
}
}
好了,这样就大功告成了