码迷,mamicode.com
首页 > 移动开发 > 详细

iOS 获取联系人,并调用系统地址簿UI

时间:2015-07-28 21:00:16      阅读:167      评论:0      收藏:0      [点我收藏+]

标签:

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 = [[ABPeoplePickerNavigationController alloc] init];

 _picker.peoplePickerDelegate  = self;

    

 self.pickerPerson = [[ABNewPersonViewController alloc] init];

 _pickerPerson.newPersonViewDelegate  = self;


//先推出 联系人列表

-(void)editContactItemBtn:(id)editItem{

    [self presentViewController:_picker animated:YES completion:nil];

}

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

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

    ABRecordRef contactPerson = person;


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

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

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


    ABMultiValueRef phonesRef = ABRecordCopyValue(contactPerson, kABPersonPhoneProperty);

    NSMutableArray * phones = [self getMobilePhoneProperty: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 = [NSDictionary dictionaryWithObjectsAndKeys: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, (__bridge CFStringRef)tempPhone, (__bridge CFStringRef)templable, &multivalueIdentifier);

    }

    ABRecordSetValue(newperson, kABPersonPhoneProperty, mulRef, NULL);

    if(mulRef)

        CFRelease(mulRef);

    

    _pickerPerson.displayedPerson =newperson;

    [self dismissViewControllerAnimated:YES completion:nil];//先把当前的miss掉,然后再推出下个

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

    [self presentViewController:nav animated:YES completion:nil];

}

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

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

    [self dismissViewControllerAnimated:YES completion:nil];

}



- (NSMutableArray *)getMobilePhoneProperty:(ABMultiValueRef)phonesRef

{

    NSMutableArray * array = [NSMutableArray array];

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

    {

        //获取电话Label

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

        //获取該Label下的电话值

        

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

        if (personPhone) {

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

            [array addObject:dic];

        }

    }

    return array;

}









版权声明:本文博客原创文章,博客,未经同意,不得转载。

iOS 获取联系人,并调用系统地址簿UI

标签:

原文地址:http://www.cnblogs.com/lcchuguo/p/4684114.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!