iOS 获取通讯录以及调用系统通讯录UI

来源:互联网 发布:手机编程百度专用皮肤 编辑:程序博客网 时间:2024/04/30 20:53

1.添加 AddressBook库

判断授权状态

-(bool)checkAddressBookAuthorizationStatus

{

    //取得授权状态

    ABAuthorizationStatus authStatus =

    ABAddressBookGetAuthorizationStatus();

    

    if (authStatus !=kABAuthorizationStatusAuthorized)

    {

       returnNO;

    }else{

       returnYES;

    }

}

注册 通讯录变更通知

-(void)createChangeCallBack{    

   CFErrorRef error =NULL;    

    myAddressBook =ABAddressBookCreateWithOptions(NULL, &error); 

}


//移除通知

- (void)unregisterCallback {

    ABAddressBookUnregisterExternalChangeCallback(myAddressBook,ContactsChangeCallback,nil);

}



收到变更通知后回调

void ContactsChangeCallback (ABAddressBookRef addressBook,

                            CFDictionaryRef info,

                            void *context){

    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT,0), ^{

ABAddressBookUnregisterExternalChangeCallback(addressBook,ContactsChangeCallback,nil);

    });

}




- (IBAction)add:(id)sender {

    ABAddressBookRequestAccessWithCompletion(ABAddressBookRef addressBookRef, ^(bool granted,CFErrorRef error) {

       if (granted) {

            dispatch_async(dispatch_get_main_queue(), ^{

              

[self getContactsFromAddressBook];

            });

        }else {

            // TODO: Show alert

        }

    });

}


-(void)getContactsFromAddressBook

{

   CFErrorRef error =NULL;

   ABAddressBookRef addressBook =ABAddressBookCreateWithOptions(NULL, &error);

    ABAddressBookRequestAccessWithCompletion(addressBook, ^(bool granted,CFErrorRef error) {

       if (granted) {

           NSArray *allContacts = (__bridge_transferNSArray*)ABAddressBookCopyArrayOfAllPeople(addressBook);

           NSMutableArray *mutableContacts = [NSMutableArrayarrayWithCapacity:allContacts.count];

           NSUInteger i =0;

           for (i =0; i<[allContactscount]; i++)

            {

               THContact *contact = [[THContactalloc]init];//封装通讯录的model

               ABRecordRef contactPerson = (__bridgeABRecordRef)allContacts[i];

                contact.recordId =ABRecordGetRecordID(contactPerson);

                

                // Get first and last names

               NSString *firstName = (__bridge_transferNSString*)ABRecordCopyValue(contactPerson,kABPersonFirstNameProperty);

               NSString *lastName = (__bridge_transferNSString*)ABRecordCopyValue(contactPerson,kABPersonLastNameProperty);

               NSString * midName = (__bridge_transferNSString*)ABRecordCopyValue(contactPerson,kABPersonMiddleNameProperty);

                

                // Set Contact properties

                contact.firstName = firstName;

                contact.lastName = lastName;

                contact.middleName = midName;

                contact.name = [contactfullName];

                // Get mobile number

               ABMultiValueRef phonesRef =ABRecordCopyValue(contactPerson,kABPersonPhoneProperty);

                contact.phone = [selfgetMobilePhoneProperty:phonesRef];

               if(phonesRef) {

                   CFRelease(phonesRef);

                }

               if (contact.phone.count >0) {

                    [mutableContactsaddObject:contact];

                }

            }

           if(addressBook) {

               CFRelease(addressBook);

            }

            //处理获取通讯后的逻辑

        }

    });

}



- (NSMutableArray *)getMobilePhoneProperty:(ABMultiValueRef)phonesRef

{

    NSMutableArray * array = [NSMutableArrayarray];

   for (int k =0; k<ABMultiValueGetCount(phonesRef); k++)

    {

        //获取电话Label

        //        NSString * personPhoneLabel = (__bridge NSString*)ABAddressBookCopyLocalizedLabel(ABMultiValueCopyLabelAtIndex(phonesRef, k));

        //获取該Label下的电话值

       NSString * personPhone = (__bridgeNSString*)ABMultiValueCopyValueAtIndex(phonesRef, k);

       if (personPhone) {

            [arrayaddObject:personPhone];

        }

    }

   return array;

}


通讯录中联系人相关的应用iPhone提供了两个框架:AddressBook.framework和AddressBookUI.framework,使用这两个框架我们可以在程序中访问并显示iPhone数据库中的联系人信息。

1.AddressBookUI显示部分

AddressBookUI中提供了和联系人显示信息相关的一些Controller,有四个:

ABPeoplePickerNavigationController:显示整个通讯录并可以选择一个联系人的信息

ABPersonViewController:显示一个具体联系人的信息

ABNewPersonViewController:增加一个新的联系人

ABUnknownPersonViewController:完善一个联系人的信息

由于其中最主要的是ABPeoplePickerNavigationController,因此就具体的介绍一下通过程序显示整个通讯录并且可以选择其中某个联系人信息的步骤。

(a)创建并初始化一个ABPeoplePickerNavigationController对象

(b)设置其代理(delegate)

(c)用presentModalViewController:animated:这个方法进行显示整个通讯录页面

例子: 项目需求,一个lable,text是一个电话,把这个电话号 添加到通讯录中得莫一个人。

#import <AddressBookUI/ABNewPersonViewController.h>

#import <AddressBookUI/ABPeoplePickerNavigationController.h>


@property (strong,nonatomic)ABPeoplePickerNavigationController *picker;

@property (strong,nonatomic)ABNewPersonViewController * pickerPerson;


 self.picker = [[ABPeoplePickerNavigationControlleralloc] init];

 _picker.peoplePickerDelegate  = self;

    

 self.pickerPerson = [[ABNewPersonViewControlleralloc] init];

 _pickerPerson.newPersonViewDelegate  =self;


//先推出 联系人列表

-(void)editContactItemBtn:(id)editItem{

    [selfpresentViewController:_pickeranimated:YEScompletion:nil];

}

//实现代理,在点击联系人列表的时候,创建一个ABRecordRef,传给添加联系人列表

- (void)peoplePickerNavigationController:(ABPeoplePickerNavigationController*)peoplePicker didSelectPerson:(ABRecordRef)person{

    ABRecordRef contactPerson = person;


    NSString *firstName = (__bridge_transferNSString*)ABRecordCopyValue(contactPerson,kABPersonFirstNameProperty);

    NSString *lastName = (__bridge_transferNSString*)ABRecordCopyValue(contactPerson,kABPersonLastNameProperty);

    NSString * midName = (__bridge_transferNSString*)ABRecordCopyValue(contactPerson,kABPersonMiddleNameProperty);


    ABMultiValueRef phonesRef =ABRecordCopyValue(contactPerson,kABPersonPhoneProperty);

    NSMutableArray * phones = [selfgetMobilePhoneProperty:phonesRef];

    if(phonesRef) {

        CFRelease(phonesRef);

    }

    ABRecordRef newperson = ABPersonCreate();


    ABRecordSetValue(newperson, kABPersonFirstNameProperty, CFBridgingRetain(firstName),NULL);

    ABRecordSetValue(newperson,kABPersonMiddleNameProperty,CFBridgingRetain(midName), NULL);

    ABRecordSetValue(newperson, kABPersonLastNameProperty, CFBridgingRetain(lastName),NULL);

    

    NSString * phone = @"13212345678";

    NSString * label = @"其他";

    

    NSDictionary * dic = [NSDictionarydictionaryWithObjectsAndKeys:phone,@"phone",label,@"lable",nil];

    [phones addObject:dic];

    

    

    ABMutableMultiValueRef mulRef =ABMultiValueCreateMutable(kABMultiStringPropertyType);


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

        NSDictionary * tempDic = [phones objectAtIndex:i];

        NSString * tempPhone = [tempDic objectForKey:@"phone"];

        NSString * templable = [tempDic objectForKey:@"lable"];

        ABMultiValueIdentifier multivalueIdentifier;

        ABMultiValueAddValueAndLabel(mulRef, (__bridgeCFStringRef)tempPhone, (__bridgeCFStringRef)templable, &multivalueIdentifier);

    }

    ABRecordSetValue(newperson, kABPersonPhoneProperty, mulRef, NULL);

    if(mulRef)

        CFRelease(mulRef);

    

    _pickerPerson.displayedPerson =newperson;

    [selfdismissViewControllerAnimated:YEScompletion:nil];//先把当前的miss掉,然后再推出下个

    UINavigationController * nav = [[UINavigationControlleralloc]initWithRootViewController:_pickerPerson];

    [selfpresentViewController:nav animated:YEScompletion:nil];

}

//添加联系人页面,不用区分是取消还是完成,系统的功能,不用自己写了

- (void)newPersonViewController:(ABNewPersonViewController *)newPersonView didCompleteWithNewPerson:(ABRecordRef)person{

    [selfdismissViewControllerAnimated:YEScompletion:nil];

}



- (NSMutableArray *)getMobilePhoneProperty:(ABMultiValueRef)phonesRef

{

    NSMutableArray * array = [NSMutableArrayarray];

    for (int k =0; k<ABMultiValueGetCount(phonesRef); k++)

    {

        //获取电话Label

                NSString * personPhoneLabel = (__bridgeNSString*)ABAddressBookCopyLocalizedLabel(ABMultiValueCopyLabelAtIndex(phonesRef, k));

        //获取該Label下的电话值

        

        NSString * personPhone = (__bridgeNSString*)ABMultiValueCopyValueAtIndex(phonesRef, k);

        if (personPhone) {

            NSDictionary * dic = [NSDictionarydictionaryWithObjectsAndKeys:personPhone,@"phone",personPhoneLabel,@"lable",nil];

            [array addObject:dic];

        }

    }

    return array;

}









0 0
原创粉丝点击