iOS.访问通讯录.01.读取联系人信息

1、相关函数介绍

1、创建通讯录对象函数

ABAddressBookRef ABAddressBookCreateWithOptions(

  CFDictionaryRef options,

  CFErrorRef *error

);

例子:

CFErrorRef error = NULL;

ABAdressBookRef addressBook = ABAdressBookCreateWithOptions(NULL,&error);

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

  if(granted){

    // 查询 ......

  }

});

CFRelease(addressBook);

2、查询联系人记录函数

CFArrayRef ABAddressBookCopyArrayOfAllPeople(

  ABAddressBookRef addressBook

);

CFArrayRef ABAddressBookCopyPeopleWithName(

  ABAddressBookRef addressBook,

  CFStringRef name

);

例子:

CFErrorRef error = NULL;

ABAdressBookRef addressBook = ABAdressBookCreateWithOptions(NULL,&error);

NSArray *listContacts = CFBridgingRelease(ABAddressBookCopyArrayOfAllPeople(addressBook));

3、读取单值属性函数

CFTypeRef ABRecordCopyValue(

  ABRecordRef record,

  ABPropertyID property

);

例子:

ABRecordRef thisPerson = CFBridgingRetain(listContacts objectAtIndex:0);

NSString *firstName  = CFBridgingRelease(ABRecordCopyValue(thisPerson,kABPersonFirstNameProperty));

NSString *lastName = CFBridgingRelease(ABRecordCopyValue(thisPerson,kABPersonLastNameProperty));

CFRelease(thisPerson);

4、读取多值属性函数

同样使用ABRecordCopyValue,但返回值为ABMultiValueRef:

ABMultiValueRef ABRecordCopyValue(

  ABRecordRef record,

  ABPropertyID property

);

例子:

ABRecordRef thisPerson = ABAddressBookGetPersonWithRecordID(addressBook,personID);

ABMultiValueRef emailsProperty = ABRecordCopyValue(thisPerson,kABPersonEmailProperty));

5、从ABMultiValueRef对象返回CFArrayRef数组

CFArrayRef ABMultiValueCopyArrayOfAllValues(

  ABMultiValueRef multiValue

);

例子:

NSArray *emailsArray = CFBridgingRelease(ABMultiValueCopyArrayOfAllValues(emailsProperty));

6、从ABMultiValueRef对象返回CFStringRef标签

CFStringRef ABMultiValueCopyLabelAtIndex(

  ABMultiValueRef multiValue,

  CFIndex index

);

例子:

NSString *emailLabel = CFBridgingRelease(ABMultiValueCopyLabelAtIndex(emailsProperty,index));

7、读取图片属性函数

CFDataRef ABPersonCopyImageData(

  ABRecordRef person

); 

例子:

if(ABPersonHasImageData(person)){

  NSData *photoData = CFBridgingRelease(ABPersonCopyImageData(person));

  if(photoData){

    ......
  }

}

2、案例代码

#import <UIKit/UIKit.h>
#import <AddressBook/AddressBook.h>

#import "T20140622175801DetailViewController.h"

@interface T20140622175801ViewController : UITableViewController
<UISearchBarDelegate, UISearchDisplayDelegate>

@property (nonatomic, strong) NSArray *listContacts;

- (void)filterContentForSearchText:(NSString*)searchText;

@end
#import "T20140622175801ViewController.h"

@interface T20140622175801ViewController ()

@end

@implementation T20140622175801ViewController

- (void)viewDidLoad
{
    [super viewDidLoad];

    CFErrorRef error = NULL;
    ABAddressBookRef addressBook = ABAddressBookCreateWithOptions(NULL, &error);
    ABAddressBookRequestAccessWithCompletion(addressBook, ^(bool granted, CFErrorRef error) {

        if (granted) {
            //查询所有
            [self filterContentForSearchText:@""];
        }

    });

    CFRelease(addressBook);
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)filterContentForSearchText:(NSString*)searchText
{
    //如果没有授权则退出
    if (ABAddressBookGetAuthorizationStatus() != kABAuthorizationStatusAuthorized) {
        return ;
    }

    CFErrorRef error = NULL;
    ABAddressBookRef addressBook = ABAddressBookCreateWithOptions(NULL, &error);

    if([searchText length]==0)
    {
        //查询所有
        self.listContacts = CFBridgingRelease(ABAddressBookCopyArrayOfAllPeople(addressBook));
    } else {
        //条件查询
        CFStringRef cfSearchText = (CFStringRef)CFBridgingRetain(searchText);
        self.listContacts = CFBridgingRelease(ABAddressBookCopyPeopleWithName(addressBook, cfSearchText));
        CFRelease(cfSearchText);
    }

    [self.tableView  reloadData];

    CFRelease(addressBook);

}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [self.listContacts count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];

    }

    ABRecordRef thisPerson = CFBridgingRetain([self.listContacts objectAtIndex:[indexPath row]]);

    NSString *firstName = CFBridgingRelease(ABRecordCopyValue(thisPerson, kABPersonFirstNameProperty));
    firstName = firstName != nil?firstName:@"";
    NSString *lastName =  CFBridgingRelease(ABRecordCopyValue(thisPerson, kABPersonLastNameProperty));
    lastName = lastName != nil?lastName:@"";
    cell.textLabel.text = [NSString stringWithFormat:@"%@ %@",firstName,lastName];
    NSString* name = CFBridgingRelease(ABRecordCopyCompositeName(thisPerson));
    cell.textLabel.text = name;

    CFRelease(thisPerson);

    return cell;
}

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    if ([[segue identifier] isEqualToString:@"showDetail"]) {
        NSIndexPath *indexPath = [self.tableView indexPathForSelectedRow];

        ABRecordRef thisPerson = CFBridgingRetain([self.listContacts objectAtIndex:[indexPath row]]);
        T20140622175801DetailViewController *detailViewController = [segue destinationViewController];

        ABRecordID personID = ABRecordGetRecordID(thisPerson);
        NSNumber *personIDAsNumber = [NSNumber numberWithInt:personID];
        detailViewController.personIDAsNumber = personIDAsNumber;

        CFRelease(thisPerson);
    }
}

#pragma mark --UISearchBarDelegate 协议方法
- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar
{
    //查询所有
    [self filterContentForSearchText:@""];
}

#pragma mark - UISearchDisplayController Delegate Methods
//当文本内容发生改变时候,向表视图数据源发出重新加载消息
- (BOOL)searchDisplayController:(UISearchDisplayController *)controller shouldReloadTableForSearchString:(NSString *)searchString
{
    [self filterContentForSearchText:searchString];
    //YES情况下表视图可以重新加载
    return YES;
}

@end
#import <UIKit/UIKit.h>
#import <AddressBook/AddressBook.h>

@interface T20140622175801DetailViewController : UITableViewController

@property (weak, nonatomic) IBOutlet UIImageView *imageView;

@property (weak, nonatomic) IBOutlet UILabel *lblName;
@property (weak, nonatomic) IBOutlet UILabel *lblMobile;

@property (weak, nonatomic) IBOutlet UILabel *lblIPhone;
@property (weak, nonatomic) IBOutlet UILabel *lblWorkEmail;
@property (weak, nonatomic) IBOutlet UILabel *lblHomeEmail;

@property (strong, nonatomic) NSNumber* personIDAsNumber;

@end
#import "T20140622175801DetailViewController.h"

@interface T20140622175801DetailViewController ()

@end

@implementation T20140622175801DetailViewController

- (id)initWithStyle:(UITableViewStyle)style
{
    self = [super initWithStyle:style];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];

    // Uncomment the following line to preserve selection between presentations.
    // self.clearsSelectionOnViewWillAppear = NO;

    // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
    // self.navigationItem.rightBarButtonItem = self.editButtonItem;

    ABRecordID personID = [self.personIDAsNumber intValue];
    CFErrorRef error = NULL;
    ABAddressBookRef addressBook = ABAddressBookCreateWithOptions(NULL, &error);

    ABRecordRef person = ABAddressBookGetPersonWithRecordID(addressBook, personID);

    //取得姓名属性
    NSString *firstName = CFBridgingRelease(ABRecordCopyValue(person, kABPersonFirstNameProperty));
    firstName = firstName != nil?firstName:@"";
    NSString *lastName =  CFBridgingRelease(ABRecordCopyValue(person, kABPersonLastNameProperty));
    lastName = lastName != nil?lastName:@"";
    [self.lblName setText: [NSString stringWithFormat:@"%@ %@",firstName,lastName]];
    NSString* name = CFBridgingRelease(ABRecordCopyCompositeName(person));
    [self.lblName setText: name];

    //取得Email属性
    ABMultiValueRef emailsProperty = ABRecordCopyValue(person, kABPersonEmailProperty);
    NSArray* emailsArray = CFBridgingRelease(ABMultiValueCopyArrayOfAllValues(emailsProperty));
    for(int index = 0; index< [emailsArray count]; index++){
        NSString *email = [emailsArray objectAtIndex:index];
        NSString *emailLabel = CFBridgingRelease(ABMultiValueCopyLabelAtIndex(emailsProperty, index));

        if ([emailLabel isEqualToString:(NSString*)kABWorkLabel]) {
            [self.lblWorkEmail setText:email];
        } else if ([emailLabel isEqualToString:(NSString*)kABHomeLabel]) {
            [self.lblHomeEmail setText:email];
        } else {
            NSLog(@"%@: %@", @"其它Email", email);
        }
    }
    CFRelease(emailsProperty);

    //取得电话号码属性
    ABMultiValueRef phoneNumberProperty = ABRecordCopyValue(person, kABPersonPhoneProperty);
    NSArray* phoneNumberArray = CFBridgingRelease(ABMultiValueCopyArrayOfAllValues(phoneNumberProperty));
    for(int index = 0; index< [phoneNumberArray count]; index++){
        NSString *phoneNumber = [phoneNumberArray objectAtIndex:index];
        NSString *phoneNumberLabel = CFBridgingRelease(ABMultiValueCopyLabelAtIndex(phoneNumberProperty, index));

        if ([phoneNumberLabel isEqualToString:(NSString*)kABPersonPhoneMobileLabel]) {
            [self.lblMobile setText:phoneNumber];
        } else if ([phoneNumberLabel isEqualToString:(NSString*)kABPersonPhoneIPhoneLabel]) {
            [self.lblIPhone setText:phoneNumber];
        } else {
            NSLog(@"%@: %@", @"其它电话", phoneNumber);
        }
    }
    CFRelease(phoneNumberProperty);

    //取得个人图片
    if (ABPersonHasImageData(person)) {
        NSData *photoData = CFBridgingRelease(ABPersonCopyImageData(person));
        if(photoData){
            [self.imageView setImage:[UIImage imageWithData:photoData]];
        }
    }

    CFRelease(addressBook);
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end

iOS.访问通讯录.01.读取联系人信息

时间: 2024-12-26 03:26:38

iOS.访问通讯录.01.读取联系人信息的相关文章

iOS.访问通讯录.02.写入联系人

一.创建联系人 1.创建联系人记录 ABRecord person = ABPersonCreate(); 2.保存或修改单值属性 bool ABRecordSetValue( ABRecordRef record, ABPropertyID property, CFTypeRef value, CFErrorRef *error ); 例子: CFError error = NULL; // 保存姓名 ABRecordSetValue(person,kABPersonFirstNameProp

iOS.访问通讯录.00.概述

1.移动设备上都有一个很重要的内置数据库 -- 通讯录,苹果把它扩展到了iCloud上,使苹果设备间可以共享通讯录信息. 2.在iOS上,通讯录放在SQLite3数据库中,但是应用之间不能直接访问,也就是说我们自己编写的应用不能采用数据持久化技术直接访问通讯录数据库.为了实现通讯录数据库的访问,苹果开放了一些专门的API. 3.处于安全考虑,iOS6之后的应用访问通讯录时,需要获得用户的授权,与其他应用(如定位服务授权)不同的是,通讯录对一个应用只授权一次,即便是这个应用删除后重新安装,也不必再

通过 ContentResolver 读取联系人信息

1.首先动态获取 读取联系人信息权限    <1>配置文件中声明对应权限 <uses-permission android:name="android.permission.READ_CONTACTS"/>    <2>判断是否具有对应权限 if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_CONTACTS) != PackageManager.PERMISSIO

iOS 访问通讯录

1.构建UI 2.向用户申请通讯录的授权 1 - (void)viewDidLoad 2 { 3 [super viewDidLoad]; 4 5 // 请求访问通讯录的权限 6 [self requestAccessAddressBook]; 7 } 8 9 // 请求访问通讯录的权限 10 - (void)requestAccessAddressBook 11 { 12 // 创建通讯录实例对象 13 ABAddressBookRef addressbook = ABAddressBookC

android之读取联系人信息

联系人信息被存放在一个contacts2.db的数据库中 主要的两张表 布局文件 在布局文件中定义一个button按钮来获取触发获取联系人信息的事件 <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="ver

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

- (IBAction)getAllContactFromSystem { ABAddressBookRef ab = ABAddressBookCreateWithOptions(NULL, NULL); ABAddressBookRequestAccessWithCompletion(ab, ^(bool granted, CFErrorRef error) { //取得通讯录访问授权 ABAuthorizationStatus authorization= ABAddressBookGet

iOS -- 从xib中读取数据信息

// App.h与App.m文件 // ViewController.m文件

iOS 修改通讯录联系人地址(address)崩溃原因分析

目前项目中需要对iOS系统通讯录进行读取,修改操作.在进行对地址修改的时候,出现了一个奇怪现象: ● 如果contact没有address字段(或者一个全新的contact),对它的address进行修改是可以成功的, ● 如果这个人有过address字段,此时对它就行修改就崩溃.控制台打出: *** -[CFString release]: message sent to deallocated instance 0x81d26f0 这应该是一个僵尸对象,重复释放某一个对象.首先我对修改通讯录

Android学习笔记(四七):Content Provider初谈和Android联系人信息

Content Provider 在数据处理中,Android通常使用Content Provider的方式.Content Provider使用Uri实例作为句柄的数据封装的,很方便地访问地进行数据的增.删.改.查的操作.Android并不提供所有应用共享的数据存储,采用content Provider,提供简单便捷的接口来保持和获取数据,也可以实现跨应用的数据访问.简单地说,Android通过content Provider从数据的封装中获取信息. Content provider使用Uri