一、在工程中添加AddressBook.framework和AddressBookUI.framework

二、获取通讯录

1、在infterface中定义数组并在init方法中初始化

1
2
3
4
5
6
NSMutableArray *addressBookTemp;
 
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    addressBookTemp = [NSMutableArray array];
}

2、定义一个model,用来存放通讯录中的各个属性

新建一个继承自NSObject的类,在.h中

1
2
3
4
5
6
7
8
9
10
11
12
13
14
@interface TKAddressBook : NSObject {
    NSInteger sectionNumber;
    NSInteger recordID;
    NSString *name;
    NSString *email;
    NSString *tel;
}
@property NSInteger sectionNumber;
@property NSInteger recordID;
@property (nonatomic, retain) NSString *name;
@property (nonatomic, retain) NSString *email;
@property (nonatomic, retain) NSString *tel;
 
@end

在.m文件中进行synthesize

1
2
3
4
@implementation TKAddressBook
@synthesize name, email, tel, recordID, sectionNumber;
 
@end

3、获取联系人

在iOS6之后,获取通讯录需要获得权限

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
    //新建一个通讯录类
    ABAddressBookRef addressBooks = nil;
 
    if ([[UIDevice currentDevice].systemVersion floatValue] >= 6.0)
 
    {
        addressBooks =  ABAddressBookCreateWithOptions(NULL, NULL);
 
        //获取通讯录权限
 
        dispatch_semaphore_t sema = dispatch_semaphore_create(0);
 
        ABAddressBookRequestAccessWithCompletion(addressBooks, ^(bool granted, CFErrorRef error){dispatch_semaphore_signal(sema);});
 
        dispatch_semaphore_wait(sema, DISPATCH_TIME_FOREVER);
 
        dispatch_release(sema);
 
    }
 
    else
 
    {
        addressBooks = ABAddressBookCreate();
 
    }
 
//获取通讯录中的所有人
CFArrayRef allPeople = ABAddressBookCopyArrayOfAllPeople(addressBooks);
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
//通讯录中人数
CFIndex nPeople = ABAddressBookGetPersonCount(addressBooks);
 
//循环,获取每个人的个人信息
for (NSInteger i = 0; i < nPeople; i++)
    {
        //新建一个addressBook model类
        TKAddressBook *addressBook = [[TKAddressBook alloc] init];
        //获取个人
        ABRecordRef person = CFArrayGetValueAtIndex(allPeople, i);
        //获取个人名字
        CFTypeRef abName = ABRecordCopyValue(person, kABPersonFirstNameProperty);
        CFTypeRef abLastName = ABRecordCopyValue(person, kABPersonLastNameProperty);
        CFStringRef abFullName = ABRecordCopyCompositeName(person);
        NSString *nameString = (__bridge NSString *)abName;
        NSString *lastNameString = (__bridge NSString *)abLastName;
         
        if ((__bridge id)abFullName != nil) {
            nameString = (__bridge NSString *)abFullName;
        } else {
            if ((__bridge id)abLastName != nil)
            {
                nameString = [NSString stringWithFormat:@"%@ %@", nameString, lastNameString];
            }
        }
        addressBook.name = nameString;
        addressBook.recordID = (int)ABRecordGetRecordID(person);;
         
        ABPropertyID multiProperties[] = {
            kABPersonPhoneProperty,
            kABPersonEmailProperty
        };
        NSInteger multiPropertiesTotal = sizeof(multiProperties) / sizeof(ABPropertyID);
        for (NSInteger j = 0; j < multiPropertiesTotal; j++) {
            ABPropertyID property = multiProperties[j];
            ABMultiValueRef valuesRef = ABRecordCopyValue(person, property);
            NSInteger valuesCount = 0;
            if (valuesRef != nil) valuesCount = ABMultiValueGetCount(valuesRef);
             
            if (valuesCount == 0) {
                CFRelease(valuesRef);
                continue;
            }
            //获取电话号码和email
            for (NSInteger k = 0; k < valuesCount; k++) {
                CFTypeRef value = ABMultiValueCopyValueAtIndex(valuesRef, k);
                switch (j) {
                    case 0: {// Phone number
                        addressBook.tel = (__bridge NSString*)value;
                        break;
                    }
                    case 1: {// Email
                        addressBook.email = (__bridge NSString*)value;
                        break;
                    }
                }
                CFRelease(value);
            }
            CFRelease(valuesRef);
        }
        //将个人信息添加到数组中,循环完成后addressBookTemp中包含所有联系人的信息
        [addressBookTemp addObject:addressBook];
         
        if (abName) CFRelease(abName);
        if (abLastName) CFRelease(abLastName);
        if (abFullName) CFRelease(abFullName);
    }

三、显示在table中

1
2
3
4
5
6
7
8
9
//行数
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}
 
//列数
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return [addressBookTemp count];
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
//cell内容
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
     
    NSString *cellIdentifier = @"ContactCell";
     
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
     
    if (cell == nil){
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:cellIdentifier];
    }
 
    TKAddressBook *book = [addressBookTemp objectAtIndex:indexPath.row];
 
    cell.textLabel.text = book.name;
 
    cell.detailTextLabel.text = book.tel;
 
    return cell;
}

列表效果

PS:通讯录中电话号码中的"-"可以在存入数组之前进行处理,属于NSString处理的范畴,解决办法有很多种,本文不多加说明

 
 

[转]iOS技巧之获取本机通讯录中的内容,解析通讯录源代码的更多相关文章

  1. javascript怎么获取指定url网页中的内容

    javascript怎么获取指定url网页中的内容 一.总结 一句话总结:推荐jquery中ajax,简单方便. 1.js能跨域操作么? javascript出于安全机制不允许跨域操作的. 二.用ph ...

  2. IOS 开发之--获取真机的deviceToeken

    获取真机的devicetoken的方法: #pragma mark 注册APNs成功并上报DeviceToken - (void)application:(UIApplication *)applic ...

  3. linux shell 脚本获取和替换文件中特定内容

    1.从一串字符串中获取特定的信息 要求1:获取本机IP:menu.lst为系统镜象的IP配置文件,需要从中获取到本机IP信息(从文件获取信息) timeout title live find --se ...

  4. win32 获取 HotKey 控件中的内容(HKM_GETHOTKEY)

    windows给我们提供了一个对话框控件HotKey非常好用,在设置热键的时候用起来很爽,但是一直百度就是没找到在win32下怎样通过消息获取这个控件里面的内容,找到的都是用MFC封装好的控件类来操作 ...

  5. IOS 开发之 -- 获取本机通讯录里面所有的联系人,并传到后台

    项目中遇到一个需求,就是需要在入口的时候,获取通讯录的权限,并把所有的联系人,以接口参数的形式传到后台,通过网上查资料,历时3个小时,终于完成, 话不多,直接上代码: 1,导入系统库 #import ...

  6. [iOS]技巧集锦:UITableView自定义Cell中的控件无法完全对齐Cell的左边界和右边界

    这是个很诡异的问题,由于一些特殊需求,我的TableView的Cell的背景色是透明,其中的控件会有背景色,第一个控件和最后一个控件我都用IB自动设了约束,对齐Cell的左边界和右边界,但是自动约束很 ...

  7. 正则获取 某段 DIV 中 的内容

    string html = "<div class='aa'><div class='left'>324324<div>dsfsdf</div> ...

  8. 获取HttpServletRequest请求Body中的内容

    在实际开发过程中,经常需要从 HttpServletRequest 中读取HTTP请求的body内容,俗话说的好”好记性不如烂笔头“,特在此将其读取方法记录一下. import java.io.Buf ...

  9. 以字符串形式获取excel单元格中的内容

    public static String getCellValue(XSSFCell cell) { if (cell == null) { return ""; } switch ...

随机推荐

  1. MySQL 体系结构以及各种文件类型学习汇总 (转)

    1,mysql体系结构 由数据库和数据库实例组成,是单进场多线程架构. 数据库:物理操作系统文件或者其它文件的集合,在mysql中,数据库文件可以是frm.myd.myi.ibd等结尾的文件,当使用n ...

  2. DW(五):polybase集群安装

    目录: Prerequisites 集群配置规划 polybase install firewall config 集群配置 删除计算节点 install Prerequisites Microsof ...

  3. Hibernate3回顾-5-简单介绍Hibernate session对数据的增删改查

    5. Hibernate对数据的增删改查 5.1Hibernate加载数据 两种:get().load() 一. Session.get(Class arg0, Serializable arg1)方 ...

  4. 【jmeter】HTTP属性管理器HTTP Cookie Manager、HTTP Request Defaults

    Test Plan的配置元件中有一些和HTTP属性相关的元件:HTTP Cache Manager.HTTP Authorization Manager.HTTP Cookie Manager.HTT ...

  5. IntelliJ IDEA自动去掉行尾空格

    Settings→Editor→General 先选中Allow placement of caret after end of line 再修改Strip trailing spaces on Sa ...

  6. MySQL瘦身

    解压mysql-x.y.z-win32|64.zip 删除不用的目录:保留bin.data.share三个文件夹 删除bin里的多余文件:保留mysqld.exe.mysqladmin.exe (如果 ...

  7. bzoj1346: [Baltic2006]Coin

    Description 有一个国家,流通着N种面值的硬币,其中包括了1分硬币.另外,有一种面值为K分的纸币,它超过了所有硬币的面值. 有一位硬币收藏家,他想收集每一种面值的硬币样本.他家里已经有一些硬 ...

  8. Python try/except/finally应用

    1.通过if和else处理异常 import os if os.path.exists('sketch.txt'): data = open ('sketch.txt') for each_line ...

  9. oracle学习笔记(二)设置归档模式

    设置归档模式(mount状态) ALTER database ARCHIVELOG; //关闭数据库 shutdown immediate //启动数据库到mount状态 startup mount ...

  10. 我的Android最佳实践之—— ImageView中图片拉伸显示

    通过设置android:scaleType="fitXY"使得图片拉伸显示.补充:scaleType的属性有matrix(默认).center.centerCrop.centerI ...