iOS9 获取手机通讯录及contact框架的使用

自iOS9开始,苹果推出新的contact框架,用户读取手机通讯录,准备废弃以前的AddressBook框架,就两者进行比较,使用contact框架非常方便,不像AddressBook框架那样麻烦,而且AddressBook使用的不是Objective-C的语法。
1.不使用contactUI:
  •  读取手机联系人在tableView上显示。

//

//  ViewController.m

//  iOS9_全新获取联系人01

//

//  Created by 高宇 on 16/6/28.

//  Copyright © 2016 高宇. All rights reserved.

//


#import "ViewController.h"

#import "DetailViewController.h"

#import


@interface ViewController ()


@end


@implementation ViewController


- (void)viewDidLoad {

    [super viewDidLoad];

    [self createTableView];

    

}


- (void)viewWillAppear:(BOOL)animated

{

    [self getContactData];

}


- (NSMutableArray *)listData

{

    if (_listData == nil) {

        _listData = [NSMutableArray array];

    }

    return _listData;

}

//获取联系人信息,并赋值给listData数组中

- (void)getContactData

{

   

    if ([CNContactStore authorizationStatusForEntityType:CNEntityTypeContacts] ==CNAuthorizationStatusAuthorized) {

        CNContactStore *stroe = [[CNContactStore alloc] init];

        [stroe requestAccessForEntityType:CNEntityTypeContacts completionHandler:^(BOOL granted, NSError* _Nullable error) {

            if (granted) {

                [self.listData removeAllObjects];

                CNContactStore *stroe = [[CNContactStore allocinit];

                NSArray *keys = @[CNContactGivenNameKey,CNContactFamilyNameKey,CNContactPhoneNumbersKey];

                CNContactFetchRequest *request = [[CNContactFetchRequest alloc] initWithKeysToFetch:keys];

                [stroe enumerateContactsWithFetchRequest:request error:nil usingBlock:^(CNContact *_Nonnull contact, BOOL * _Nonnull stop) {

                    

                    [self.listData addObject:contact];

                    [_tableView reloadData];

                    

                }];

            }else{

            }

        }];

    }

}



- (void)createTableView

{

    _tableView = [[UITableView alloc] initWithFrame:self.view.bounds style:UITableViewStylePlain];

    _tableView.delegate = self;

    _tableView.dataSource = self;

    [self.view addSubview:_tableView];

}


- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView

{

    return 1;

}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section

{

    return self.listData.count;

}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath*)indexPath

{

    CNContact *contact = self.listData[indexPath.row];

    static NSString *ID = @"cell";

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:ID];

    if (!cell) {

        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:ID];

    }

    cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;

    NSString *givenName = contact.givenName;

    NSString *familyName = contact.familyName;

    cell.textLabel.text = [NSString stringWithFormat:@"%@ %@",givenName,familyName];

    return cell;

}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath

{

    CNContact *contact = self.listData[indexPath.row];

    DetailViewController *detail = [[DetailViewController alloc] init];

    detail.contact = contact;

    [self.navigationController pushViewController:detail animated:YES];

    

}

- (void)didReceiveMemoryWarning {

    [super didReceiveMemoryWarning];

    // Dispose of any resources that can be recreated.

}

@end

  • 运行结果如图所示:


  • 读取联系人详细信息:

//

//  DetailViewController.m

//  iOS9_全新获取联系人01

//

//  Created by 高宇 on 16/6/28.

//  Copyright © 2016 高宇. All rights reserved.

//


#import "DetailViewController.h"

#import

@interface DetailViewController ()


@property (weaknonatomicUILabel *firstNameLabel;

@property (weaknonatomicUITextField *firstNameField;

@property (weaknonatomicUILabel *lastNameLabel;

@property (weaknonatomicUITextField *lastNameField;

@property (weaknonatomicUILabel *homePhoneLabel;

@property (weaknonatomicUITextField *homePhoneField;

@property (weak, nonatomic) UILabel *iPhoneLabel;

@property (weak, nonatomic) UITextField *iPhoneField;



@end


@implementation DetailViewController


- (void)viewDidLoad {

    [super viewDidLoad];

    self.title = @"联系人";

    self.view.backgroundColor = [UIColor whiteColor];

    

//    UIBarButtonItem *leftItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemCancel target:self action:@selector(CANCEL)];

//    self.navigationItem.leftBarButtonItem = leftItem;

    

//    UIBarButtonItem *item = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemSave target:self action:@selector(SAVE)];

//    self.navigationItem.rightBarButtonItem = item;

    

    [self createUI];

    [self setData];

}


- (void)createUI

{

    UILabel *firstNameLabel = [[UILabel allocinitWithFrame:CGRectMake(208410040)];

    firstNameLabel.text = @"姓氏:";

    self.firstNameLabel = firstNameLabel;

    [self.view addSubview:firstNameLabel];

    UITextField *firstNameField = [[UITextField allocinitWithFrame:CGRectMake(13084,self.view.frame.size.width - 23040)];

    firstNameField.placeholder = @"如:张";

    self.firstNameField = firstNameField;

    [self.view addSubview:firstNameField];

    

    UILabel *lastNameLabel = [[UILabel allocinitWithFrame:CGRectMake(20,CGRectGetMaxY(firstNameLabel.frame) + 1010040)];

    lastNameLabel.text = @"名字";

    self.lastNameLabel = lastNameLabel;

    [self.view addSubview:lastNameLabel];

    UITextField *lastNameField = [[UITextField alloc] initWithFrame:CGRectMake(130, CGRectGetMaxY(firstNameLabel.frame) + 10, firstNameField.frame.size.width, 40)];

    lastNameField.placeholder = @":";

    self.lastNameField = lastNameField;

    [self.view addSubview:lastNameField];

    

    UILabel *homePhoneLabel = [[UILabel alloc] initWithFrame:CGRectMake(20, CGRectGetMaxY(lastNameLabel.frame) + 2010040)];

    homePhoneLabel.text = @"Home电话:";

    self.homePhoneLabel = homePhoneLabel;

    [self.view addSubview:homePhoneLabel];

    UITextField *homePhoneField = [[UITextField alloc] initWithFrame:CGRectMake(130, CGRectGetMaxY(lastNameLabel.frame) + 20self.view.frame.size.width - 23040)];

    homePhoneField.placeholder = @"如:186-0078-9685";

    self.homePhoneField = homePhoneField;

    [self.view addSubview:homePhoneField];

    

    UILabel *iPhoneLabel = [[UILabel alloc] initWithFrame:CGRectMake(20, CGRectGetMaxY(homePhoneLabel.frame) + 1010040)];

    iPhoneLabel.text = @"iPhone电话:";

    self.iPhoneLabel = iPhoneLabel;

    [self.view addSubview:iPhoneLabel];

    UITextField *iPhoneField = [[UITextField alloc] initWithFrame:CGRectMake(130, CGRectGetMaxY(homePhoneLabel.frame) + 10, firstNameField.frame.size.width, 40)];

    iPhoneField.placeholder = @":186-0078-9685";

    self.iPhoneField = iPhoneField;

    [self.view addSubview:iPhoneField];

    

}

//对获取的联系人信息复制到textField

- (void)setData

{

    self.firstNameField.text = self.contact.givenName;

    self.lastNameField.text = self.contact.familyName;

    NSArray *phoneArray = self.contact.phoneNumbers;

    for (CNLabeledValue *value in phoneArray) {

        CNPhoneNumber *phone = value.value;

        NSLog(@"%@",value.label);

        if ([value.label rangeOfString:@"Home"].location == NSNotFound) {

            self.homePhoneField.text = phone.stringValue;

        }else{

            self.iPhoneField.text = phone.stringValue;

        }

    }

}

//更新联系人信息

- (void)SAVE

{

    [self.navigationController popViewControllerAnimated:YES];

//    CNMutableContact *contact = [[CNMutableContact alloc] init];

    (CNMutableContact *)self.contact;

//    contact.givenName = self.firstNameField.text;

//    contact.familyName = self.lastNameField.text;

//    contact.phoneNumbers = @[[CNLabeledValue labeledValueWithLabel:CNLabelPhoneNumberHomeFax value:[CNPhoneNumber phoneNumberWithStringValue:self.homePhoneField.text]], [CNLabeledValue labeledValueWithLabel:CNLabelPhoneNumberMobile value:[CNPhoneNumber phoneNumberWithStringValue:self.iPhoneField.text]]];

//    self.contact = contact;

//    CNSaveRequest *request = [[CNSaveRequest alloc] init];

//    [request updateContact:contact];

//    CNContactStore *store = [[CNContactStore alloc] init];

//    [store executeSaveRequest:request error:nil];

}


- (void)didReceiveMemoryWarning {

    [super didReceiveMemoryWarning];

    // Dispose of any resources that can be recreated.

}

@end

 

  • 结果如图所示:

  • 增加联系人信息:

//

//  AddViewController.m

//  iOS9_全新获取联系人01

//

//  Created by 高宇 on 16/6/28.

//  Copyright © 2016 高宇. All rights reserved.

//


#import "AddViewController.h"

#import


@interface AddViewController ()

- (IBAction)Cancel:(id)sender;

- (IBAction)Save:(id)sender;

@property (weak, nonatomic) IBOutlet UITextField *firstNameField;

@property (weak, nonatomic) IBOutlet UITextField *lastNameField;

@property (weak, nonatomic) IBOutlet UITextField *homePhoneField;

@property (weak, nonatomic) IBOutlet UITextField *IPhoneField;


@end


@implementation AddViewController


- (void)viewDidLoad {

    [super viewDidLoad];

    // Do any additional setup after loading the view.

}


- (void)didReceiveMemoryWarning {

    [super didReceiveMemoryWarning];

    // Dispose of any resources that can be recreated.

}



- (IBAction)Cancel:(id)sender {

    [self.navigationController popViewControllerAnimated:YES];

}


- (IBAction)Save:(id)sender {

    CNMutableContact *contact = [[CNMutableContact alloc] init];

    contact.givenName = self.firstNameField.text;

    contact.familyName = self.lastNameField.text;

    contact.phoneNumbers = @[[CNLabeledValue labeledValueWithLabel:CNLabelPhoneNumberHomeFax value:[CNPhoneNumber phoneNumberWithStringValue:self.homePhoneField.text]], [CNLabeledValuelabeledValueWithLabel:CNLabelPhoneNumberMobile value:[CNPhoneNumberphoneNumberWithStringValue:self.IPhoneField.text]]];

    CNSaveRequest *request = [[CNSaveRequest alloc] init];

    [request addContact:contact toContainerWithIdentifier:nil];

    CNContactStore *store = [[CNContactStore alloc] init];

    [store executeSaveRequest:request error:nil];

    [self.navigationController popViewControllerAnimated:YES];

}

@end

 

  • 运行结果如图所示:


2.对于contactUI的使用就非常方便就几句代码就可以搞定

 CNContactPickerViewController *vc = [[CNContactPickerViewController alloc] init];

    vc.delegate = self;

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

这样就搞定了 ,是不是很简单个啊,最后祝大家的技术一天比一天好。

 


  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值