技术文章分类(180)

技术随笔(11)

ios通讯录基本操作2014-12月版

github 下载demo:https://github.com/MartinLi841538513/MartinDemos (一切以demo为准)

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

1.AddressBookUI显示部分

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

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

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

ABNewPersonViewController:增加一个新的联系人

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

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

其实很简单,只是网上的资料很乱,会迷惑人。估计大家看代码很容易能懂。

1,添加AddressBook.framework和AddressBookUI.framework框架

2,在对应的文件#import <AddressBookUI/AddressBookUI.h>,集成实现ABPeoplePickerNavigationControllerDelegate

实现didSelectPerson:方法。其实操作基本就完成了,只是获取联系人数据应该是用c语言的封装的,所以稍微有些不一样,但是还是隐瞒不了他是很简单的事实。

#import "ContactsViewController.h"
#import <AddressBookUI/AddressBookUI.h>
@interface ContactsViewController ()<ABPeoplePickerNavigationControllerDelegate>
@end
@implementation ContactsViewController

- (IBAction)openContactsAction:(id)sender {
    ABPeoplePickerNavigationController *picker = [[ABPeoplePickerNavigationController alloc] init];
    picker.peoplePickerDelegate = self;
    [self presentViewController:picker animated:YES completion:nil];
}

#pragma ABPeoplePickerNavigationControllerDelegate
// Called after a property has been selected by the user.
- (void)peoplePickerNavigationController:(ABPeoplePickerNavigationController*)peoplePicker didSelectPerson:(ABRecordRef)person property:(ABPropertyID)property identifier:(ABMultiValueIdentifier)identifier{
    ABMultiValueRef multiValue = ABRecordCopyValue(person,property);
    CFIndex index = ABMultiValueGetIndexForIdentifier(multiValue, identifier);
    NSString *phone = (__bridge NSString *)ABMultiValueCopyValueAtIndex(multiValue, index);
    self.phone.text = phone;
}

- (IBAction)callAction:(id)sender {
    NSString *tel = [NSString stringWithFormat:@"tel:%@",self.phone.text];
    UIWebView *callWebview = [[UIWebView alloc] init];
    NSURL *telURL = [NSURL URLWithString:tel];
    [callWebview loadRequest:[NSURLRequest requestWithURL:telURL]];
    [self.view addSubview:callWebview];
}
@end

 如果需要支持ios8以下的版本,那么还需要加入以下代码。

- (BOOL)peoplePickerNavigationController:(ABPeoplePickerNavigationController *)peoplePicker shouldContinueAfterSelectingPerson:(ABRecordRef)person property:(ABPropertyID)property identifier:(ABMultiValueIdentifier)identifier{
    
    ABMultiValueRef multiValue = ABRecordCopyValue(person,property);
    CFIndex index = ABMultiValueGetIndexForIdentifier(multiValue, identifier);
    NSString *phone1 = (__bridge NSString *)ABMultiValueCopyValueAtIndex(multiValue, index);
    //    [call CallPhoneWithMid:mid AndPhone:phone1 OnViewCOntroller:self];
    self.phone.text = phone1;
    [peoplePicker dismissViewControllerAnimated:YES completion:nil];
    return NO;
}

这里一定要return NO;不然就直接打电话出去了。

posted @ 2014-12-04 19:18  坤哥MartinLi  阅读(344)  评论(0编辑  收藏  举报