iOS -------- 应用程序引用系统通讯录

转自:http://www.cnblogs.com/ygm900/p/3472288.html

由于ios系统对用户隐私的控制,第三方应用程序只能通过苹果官方接口调用系统通讯录,不能像android那样直接操作通讯录数据库。
     一般地,使用系统自带通讯录的方法有两种,一种是直接将整个通讯录引入到应用程序,另一种是逐条读取通讯录中的每一条联系人信息。下面我们就一一详解。

1 直接引用整个通讯录

使用的类:ABPeoplePickerNavigationController
方法:

在LocalAddressBookController.h文件中
#import <UIKit/UIKit.h>
#import <AddressBook/AddressBook.h>
#import <AddressBookUI/AddressBookUI.h>
@interface LocalAddressBookController : UIViewController<ABPersonViewControllerDelegate,ABPeoplePickerNavigationControllerDelegate,ABNewPersonViewControllerDelegate>
{
    ABPeoplePickerNavigationController *picker;
    ABNewPersonViewController *personViewController;
}
@end

在LocalAddressBookController.m文件中
#import "LocalAddressBookController.h"
#import "PublicHeader.h"

@implementation LocalAddressBookController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn‘t have a superview.
    [super didReceiveMemoryWarning];

    // Release any cached data, images, etc that aren‘t in use.
}

#pragma mark - View lifecycle

- (void)viewDidLoad
{
    [super viewDidLoad];

    picker = [[ABPeoplePickerNavigationController alloc]init];
    picker.view.frame = CGRectMake(0, 0, Screen_width, Screen_height-48);
    picker.peoplePickerDelegate = self;
    picker.delegate = self;                   //为了隐藏右上角的“取消”按钮
    [picker setHidesBottomBarWhenPushed:YES];
    [picker setNavigationBarHidden:NO animated:NO];//显示上方的NavigationBar和搜索框
    [self.view addSubview:picker.view];
}

#pragma mark UINavigationControllerDelegate methods
//隐藏“取消”按钮
- (void)navigationController:(UINavigationController *)navigationController willShowViewController:(UIViewController *)viewController animated:(BOOL)animated
{
    UIView *custom = [[UIView alloc] initWithFrame:CGRectMake(0.0f,0.0f,0.0f,0.0f)];
    UIBarButtonItem *btn = [[UIBarButtonItem alloc] initWithCustomView:custom];
    [viewController.navigationItem setRightBarButtonItem:btn animated:NO];
    [btn release];
    [custom release];
}

#pragma mark - peoplePickerDelegate Methods
-(BOOL)peoplePickerNavigationController:(ABPeoplePickerNavigationController *)peoplePicker shouldContinueAfterSelectingPerson:(ABRecordRef)person
{
//    [picker setNavigationBarHidden:NO animated:NO];
    NSLog(@"%@", (NSString*)ABRecordCopyCompositeName(person));
    return YES;
}
-(BOOL)peoplePickerNavigationController:(ABPeoplePickerNavigationController *)peoplePicker shouldContinueAfterSelectingPerson:(ABRecordRef)person property:(ABPropertyID)property identifier:(ABMultiValueIdentifier)identifier
{

    return YES;
}
-(BOOL)personViewController:(ABPersonViewController *)personViewController shouldPerformDefaultActionForPerson:(ABRecordRef)person property:(ABPropertyID)property identifier:(ABMultiValueIdentifier)identifier{
    return YES;
}

//“取消”按钮的委托响应方法
-(void)peoplePickerNavigationControllerDidCancel:(ABPeoplePickerNavigationController *)peoplePicker
{
    //assigning control back to the main controller
    [picker dismissModalViewControllerAnimated:YES];
}
//……@end

ios6 运行效果:

ios7 运行效果:

经验:

当我们将系统通讯录整个引入的时候,在通讯录的右上角有一个系统自带的“取消”按钮。如何才能将这个取消按钮隐藏呢?

(1)方法1:如果你的应用程序是用企业证书开发,不需要提交到appStore进行审核,那么答案非常简单,为响应的piker增加如下代码即可:

[picker setAllowsCancel:NO];

(2)方法二:上面的方法是非公开方法,是无法通过appStore审核的。如果想通过审核。可以尝试使用如下方法:

前提:设置 picker.delegate = self;
然后实现如下委托方法
- (void)navigationController:(UINavigationController *)navigationController willShowViewController:(UIViewController *)viewController animated:(BOOL)animated {
  UIView *custom = [[UIView alloc] initWithFrame:CGRectMake(0.0f,0.0f,0.0f,0.0f)];
  UIBarButtonItem *btn = [[UIBarButtonItem alloc] initWithCustomView:custom];
  //UIBarButtonItem *btn = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAdd target:self action:@selector(addAction)];
  [viewController.navigationItem setRightBarButtonItem:btn animated:NO];
  [btn release];
  [custom release];
}

或者:(比上面更好)

前提:设置 picker.delegate = self;
然后实现如下委托方法,下面实现的效果,要比上面的好。上面实现的效果,当点击“搜索”框时,“取消”按钮还会重新出现。
- (void)navigationController:(UINavigationController *)navigationController
      willShowViewController:(UIViewController *)viewController
                    animated:(BOOL)animated {

    // Here we want to remove the ‘Cancel‘ button, but only if we‘re showing
    // either of the ABPeoplePickerNavigationController‘s top two controllers
    if ([navigationController.viewControllers indexOfObject:viewController] <= 1) {
        viewController.navigationItem.rightBarButtonItem = nil;
    }
}

2、逐条读取通讯录中的每一条联系人信息。

方法:在上述类中,直接添加如下方法即可

在LocalAddressBookController.h文件中
#import <UIKit/UIKit.h>
#import <AddressBook/AddressBook.h>
#import <AddressBookUI/AddressBookUI.h>
@interface LocalAddressBookController :
{
    UITextView *textView;
}
@end

在LocalAddressBookController.m文件中
#import "LocalAddressBookController.h"
#import "PublicHeader.h"

@implementation LocalAddressBookController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn‘t have a superview.
    [super didReceiveMemoryWarning];

    // Release any cached data, images, etc that aren‘t in use.
}

#pragma mark - View lifecycle

- (void)viewDidLoad
{
    [super viewDidLoad];
    textView = [[UITextView alloc]initWithFrame:CGRectMake(0, 0, Screen_width, Screen_height)];
    [self getAddressBook];
    [self.view addSubview:textView];
}

//获取通讯录中的所有属性,并存储在 textView 中,已检验,切实可行。兼容io6 和 ios 7 ,而且ios7还没有权限确认提示。
-(void)getAddressBook
{
    ABAddressBookRef addressBook = ABAddressBookCreate();

    CFArrayRef results = ABAddressBookCopyArrayOfAllPeople(addressBook);

    for(int i = 0; i < CFArrayGetCount(results); i++)
    {
        ABRecordRef person = CFArrayGetValueAtIndex(results, i);
        //读取firstname
        NSString *personName = (NSString*)ABRecordCopyValue(person, kABPersonFirstNameProperty);
        if(personName != nil)
            textView.text = [textView.text stringByAppendingFormat:@"\n姓名:%@\n",personName];
        //读取lastname
        NSString *lastname = (NSString*)ABRecordCopyValue(person, kABPersonLastNameProperty);
        if(lastname != nil)
            textView.text = [textView.text stringByAppendingFormat:@"%@\n",lastname];
        //读取middlename
        NSString *middlename = (NSString*)ABRecordCopyValue(person, kABPersonMiddleNameProperty);
        if(middlename != nil)
            textView.text = [textView.text stringByAppendingFormat:@"%@\n",middlename];
        //读取prefix前缀
        NSString *prefix = (NSString*)ABRecordCopyValue(person, kABPersonPrefixProperty);
        if(prefix != nil)
            textView.text = [textView.text stringByAppendingFormat:@"%@\n",prefix];
        //读取suffix后缀
        NSString *suffix = (NSString*)ABRecordCopyValue(person, kABPersonSuffixProperty);
        if(suffix != nil)
            textView.text = [textView.text stringByAppendingFormat:@"%@\n",suffix];
        //读取nickname呢称
        NSString *nickname = (NSString*)ABRecordCopyValue(person, kABPersonNicknameProperty);
        if(nickname != nil)
            textView.text = [textView.text stringByAppendingFormat:@"%@\n",nickname];
        //读取firstname拼音音标
        NSString *firstnamePhonetic = (NSString*)ABRecordCopyValue(person, kABPersonFirstNamePhoneticProperty);
        if(firstnamePhonetic != nil)
            textView.text = [textView.text stringByAppendingFormat:@"%@\n",firstnamePhonetic];
        //读取lastname拼音音标
        NSString *lastnamePhonetic = (NSString*)ABRecordCopyValue(person, kABPersonLastNamePhoneticProperty);
        if(lastnamePhonetic != nil)
            textView.text = [textView.text stringByAppendingFormat:@"%@\n",lastnamePhonetic];
        //读取middlename拼音音标
        NSString *middlenamePhonetic = (NSString*)ABRecordCopyValue(person, kABPersonMiddleNamePhoneticProperty);
        if(middlenamePhonetic != nil)
            textView.text = [textView.text stringByAppendingFormat:@"%@\n",middlenamePhonetic];
        //读取organization公司
        NSString *organization = (NSString*)ABRecordCopyValue(person, kABPersonOrganizationProperty);
        if(organization != nil)
            textView.text = [textView.text stringByAppendingFormat:@"%@\n",organization];
        //读取jobtitle工作
        NSString *jobtitle = (NSString*)ABRecordCopyValue(person, kABPersonJobTitleProperty);
        if(jobtitle != nil)
            textView.text = [textView.text stringByAppendingFormat:@"%@\n",jobtitle];
        //读取department部门
        NSString *department = (NSString*)ABRecordCopyValue(person, kABPersonDepartmentProperty);
        if(department != nil)
            textView.text = [textView.text stringByAppendingFormat:@"%@\n",department];
        //读取birthday生日
        NSDate *birthday = (NSDate*)ABRecordCopyValue(person, kABPersonBirthdayProperty);
        if(birthday != nil)
            textView.text = [textView.text stringByAppendingFormat:@"%@\n",birthday];
        //读取note备忘录
        NSString *note = (NSString*)ABRecordCopyValue(person, kABPersonNoteProperty);
        if(note != nil)
            textView.text = [textView.text stringByAppendingFormat:@"%@\n",note];
        //第一次添加该条记录的时间
        NSString *firstknow = (NSString*)ABRecordCopyValue(person, kABPersonCreationDateProperty);
        NSLog(@"第一次添加该条记录的时间%@\n",firstknow);
        //最后一次修改該条记录的时间
        NSString *lastknow = (NSString*)ABRecordCopyValue(person, kABPersonModificationDateProperty);
        NSLog(@"最后一次修改該条记录的时间%@\n",lastknow);

        //获取email多值
        ABMultiValueRef email = ABRecordCopyValue(person, kABPersonEmailProperty);
        int emailcount = ABMultiValueGetCount(email);
        for (int x = 0; x < emailcount; x++)
        {
            //获取email Label
            NSString* emailLabel = (NSString*)ABAddressBookCopyLocalizedLabel(ABMultiValueCopyLabelAtIndex(email, x));
            //获取email值
            NSString* emailContent = (NSString*)ABMultiValueCopyValueAtIndex(email, x);
            textView.text = [textView.text stringByAppendingFormat:@"%@:%@\n",emailLabel,emailContent];
        }
        //读取地址多值
        ABMultiValueRef address = ABRecordCopyValue(person, kABPersonAddressProperty);
        int count = ABMultiValueGetCount(address);

        for(int j = 0; j < count; j++)
        {
            //获取地址Label
            NSString* addressLabel = (NSString*)ABMultiValueCopyLabelAtIndex(address, j);
            textView.text = [textView.text stringByAppendingFormat:@"%@\n",addressLabel];
            //获取該label下的地址6属性
            NSDictionary* personaddress =(NSDictionary*) ABMultiValueCopyValueAtIndex(address, j);
            NSString* country = [personaddress valueForKey:(NSString *)kABPersonAddressCountryKey];
            if(country != nil)
                textView.text = [textView.text stringByAppendingFormat:@"国家:%@\n",country];
            NSString* city = [personaddress valueForKey:(NSString *)kABPersonAddressCityKey];
            if(city != nil)
                textView.text = [textView.text stringByAppendingFormat:@"城市:%@\n",city];
            NSString* state = [personaddress valueForKey:(NSString *)kABPersonAddressStateKey];
            if(state != nil)
                textView.text = [textView.text stringByAppendingFormat:@"省:%@\n",state];
            NSString* street = [personaddress valueForKey:(NSString *)kABPersonAddressStreetKey];
            if(street != nil)
                textView.text = [textView.text stringByAppendingFormat:@"街道:%@\n",street];
            NSString* zip = [personaddress valueForKey:(NSString *)kABPersonAddressZIPKey];
            if(zip != nil)
                textView.text = [textView.text stringByAppendingFormat:@"邮编:%@\n",zip];
            NSString* coutntrycode = [personaddress valueForKey:(NSString *)kABPersonAddressCountryCodeKey];
            if(coutntrycode != nil)
                textView.text = [textView.text stringByAppendingFormat:@"国家编号:%@\n",coutntrycode];
        }

        //获取dates多值
        ABMultiValueRef dates = ABRecordCopyValue(person, kABPersonDateProperty);
        int datescount = ABMultiValueGetCount(dates);
        for (int y = 0; y < datescount; y++)
        {
            //获取dates Label
            NSString* datesLabel = (NSString*)ABAddressBookCopyLocalizedLabel(ABMultiValueCopyLabelAtIndex(dates, y));
            //获取dates值
            NSString* datesContent = (NSString*)ABMultiValueCopyValueAtIndex(dates, y);
            textView.text = [textView.text stringByAppendingFormat:@"%@:%@\n",datesLabel,datesContent];
        }
        //获取kind值
        CFNumberRef recordType = ABRecordCopyValue(person, kABPersonKindProperty);
        if (recordType == kABPersonKindOrganization) {
            // it‘s a company
            NSLog(@"it‘s a company\n");
        } else {
            // it‘s a person, resource, or room
            NSLog(@"it‘s a person, resource, or room\n");
        }

        //获取IM多值
        ABMultiValueRef instantMessage = ABRecordCopyValue(person, kABPersonInstantMessageProperty);
        for (int l = 1; l < ABMultiValueGetCount(instantMessage); l++)
        {
            //获取IM Label
            NSString* instantMessageLabel = (NSString*)ABMultiValueCopyLabelAtIndex(instantMessage, l);
            textView.text = [textView.text stringByAppendingFormat:@"%@\n",instantMessageLabel];
            //获取該label下的2属性
            NSDictionary* instantMessageContent =(NSDictionary*) ABMultiValueCopyValueAtIndex(instantMessage, l);
            NSString* username = [instantMessageContent valueForKey:(NSString *)kABPersonInstantMessageUsernameKey];
            if(username != nil)
                textView.text = [textView.text stringByAppendingFormat:@"username:%@\n",username];

            NSString* service = [instantMessageContent valueForKey:(NSString *)kABPersonInstantMessageServiceKey];
            if(service != nil)
                textView.text = [textView.text stringByAppendingFormat:@"service:%@\n",service];
        }

        //读取电话多值
        ABMultiValueRef phone = ABRecordCopyValue(person, kABPersonPhoneProperty);
        for (int k = 0; k<ABMultiValueGetCount(phone); k++)
        {
            //获取电话Label
            NSString * personPhoneLabel = (NSString*)ABAddressBookCopyLocalizedLabel(ABMultiValueCopyLabelAtIndex(phone, k));
            //获取該Label下的电话值
            NSString * personPhone = (NSString*)ABMultiValueCopyValueAtIndex(phone, k);

            textView.text = [textView.text stringByAppendingFormat:@"%@:%@\n",personPhoneLabel,personPhone];
        }

        //获取URL多值
        ABMultiValueRef url = ABRecordCopyValue(person, kABPersonURLProperty);
        for (int m = 0; m < ABMultiValueGetCount(url); m++)
        {
            //获取电话Label
            NSString * urlLabel = (NSString*)ABAddressBookCopyLocalizedLabel(ABMultiValueCopyLabelAtIndex(url, m));
            //获取該Label下的电话值
            NSString * urlContent = (NSString*)ABMultiValueCopyValueAtIndex(url,m);

            textView.text = [textView.text stringByAppendingFormat:@"%@:%@\n",urlLabel,urlContent];
        }

        //读取照片
        NSData *image = (NSData*)ABPersonCopyImageData(person);

        UIImageView *myImage = [[UIImageView alloc] initWithFrame:CGRectMake(200, 0, 50, 50)];
        [myImage setImage:[UIImage imageWithData:image]];
        myImage.opaque = YES;
        [textView addSubview:myImage];
    }

    CFRelease(results);
    CFRelease(addressBook);
}//……@end

ios7运行效果:

参考:

想扩展右上角“取消”按钮的可以看  http://d2100.com/questions/6864

隐藏右上角“取消”按钮的方法 (有可行代码)   http://stackoverflow.com/questions/1611499/abpeoplepickernavigationcontroller-remove-cancel-button-without-using-privat

如何使用ios addressBook 总结的很全面,有概括性 http://www.cnblogs.com/y041039/archive/2012/03/22/2411771.html

时间: 2024-10-07 18:17:55

iOS -------- 应用程序引用系统通讯录的相关文章

IOS获取系统通讯录联系人信息

先导入AddressBook.framework先 然后引用  #import <AddressBook/AddressBook.h> 一.权限注册 随着apple对用户隐私的越来越重视,IOS系统的权限设置也更加严格,在获取系统通讯录之前,我们必须获得用户的授权.权限申请代码示例如下: #pragma mark - 注册权限 - (void)contacts { //这个变量用于记录授权是否成功,即用户是否允许我们访问通讯录 int __block tip = 0; //声明一个通讯簿的引用

iOS开发--系统通讯录的访问与添加联系人

公司项目有访问通讯录的需求,所以开始了探索之路.从开始的一无所知,到知识的渐渐清晰.这一切要感谢广大无私分享的 “coder”,注:我是尊称的语气! 苹果提供了访问系统通讯录的框架,以便开发者对系统通讯录进行操作.(此demo为纯代码),想要访问通讯录,需要添加AddressBookUI.framework和AddressBook.framework两个框架,添加的地点这里就不在赘述了.在控制器内部首先import两个头文件,<AddressBook/AddressBook.h> 和 <

iOS:ABPeoplePickerNavigationController系统通讯录使用

昨天因项目需求要访问系统通讯录获取电话号码,于是乎从一无所知,开始倒腾,倒腾了一下午,总算了弄好了.写这边博客是为了记录一下,自己下一次弄的时候就别在出错了.同时,有和我一样的菜鸟能够避免走一下弯路. 好了,言归正传,要访问系统的通讯录,首先需要添加AddressBook.framework和AddressBookUI.framework两个框架到你工程中build phase的"Link Binary With Libraries"之下,然后就可以开始了. 首先我们需要创建一个控制器

iOS开发之系统通讯录

@iOS调用操作通讯录所用的库文件 AddressBook.framework AddressBookUI.framework #import "HMTMainViewController.h" #import <AddressBook/AddressBook.h> #import <AddressBookUI/AddressBookUI.h> @interface HMTMainViewController ()<ABPeoplePickerNaviga

iOS --调用系统通讯录

// 调用系统通讯录需要遵循两个代理ABPeoplePickerNavigationControllerDelegate,UINavigationControllerDelegate 相关类为ABPeoplePickerNavigationController // 系统通讯录自带导航栏,所有要model出来 // 初始化 ABPeoplePickerNavigationController *peoplePicker = [[ABPeoplePickerNavigationController

iOS开发--调用系统通讯录界面

今天写代码遇到了要调用系统通讯录,看了一些博客发现写的都是获取通讯录的内容,而不是调用系统的界面. 分享一下自己写的代码 第一步:引入 #import <AddressBook/AddressBook.h> #import <AddressBookUI/AddressBookUI.h> 第二步:添加点击事件 创建一个通讯录界面 并以present的方式跳转 #pragma mark -- IBAction - (IBAction)buttonClicked:(id)sender {

IOS 获取系统通讯录

进入正题  获取系统通讯录,不想多讲,留下链接http://my.oschina.net/joanfen/blog/140146 通常做法: 首先创建一个ABAddressBookRef类的对象addressBooks,然后获取系统权限, 获取权限的代码: // 获取系统权限,并获得通讯录内容存入addressBooks. ABAddressBookRef addressBooks = nil; addressBooks = ABAddressBookCreateWithOptions(NULL

iOS开发者程序许可协议

请仔细阅读下面的许可协议条款和条件之前下载或使用苹果软件.   这些条款和条件构成你和苹果之间的法律协议. 目的 你想使用苹果软件(如下定义)来开发一个或多个应用程序(如下定义)Apple-branded产品运行iOS. 苹果愿意授予您有限的许可使用苹果软件开发和测试您的应用程序在本协议规定的条款和条件. 开发的应用程序在此协议下可以分布在四个方面:(1)通过应用程序商店,如果选择苹果,(2)通过VPP / B2B项目网站,如果选择苹果,(3)在一个有限的基础上使用注册设备(如下定义),和(4)

[转]iOS应用程序生命周期(前后台切换,应用的各种状态)详解

转载地址:http://blog.csdn.net/totogo2010/article/details/8048652 iOS的应用程序的生命周期,还有程序是运行在前台还是后台,应用程序各个状态的变换,这些对于开发者来说都是很重要的. iOS系统的资源是有限的,应用程序在前台和在后台的状态是不一样的.在后台时,程序会受到系统的很多限制,这样可以提高电池的使用和用户体验. //开发app,我们要遵循apple公司的一些指导原则,原则如下: 1.应用程序的状态 状态如下: Not running