iOS获取通讯录联系人

1、跳转通讯录

#import <ContactsUI/ContactsUI.h>
<CNContactPickerDelegate>
CNContactPickerViewController * contactVc = [CNContactPickerViewController new];
contactVc.delegate = self;
[self presentViewController:contactVc animated:YES completion:nil];

2、获取联系人

#import <Contacts/Contacts.h>
#pragma mark 点击获取通讯录权限
- (void)getAddressBookPermission{
    
    CNAuthorizationStatus status = [CNContactStore authorizationStatusForEntityType:CNEntityTypeContacts];
    if (status == CNAuthorizationStatusNotDetermined) {
        CNContactStore *store = [[CNContactStore alloc] init];
        [store requestAccessForEntityType:CNEntityTypeContacts completionHandler:^(BOOL granted, NSError*  _Nullable error) {
            if (error) {
                NSLog(@"授权失败");
            }else {
                NSLog(@"成功授权");
                [self getContact];
            }
        }];
    }
    else if(status == CNAuthorizationStatusRestricted)
    {
        NSLog(@"用户拒绝");
    }
    else if (status == CNAuthorizationStatusDenied)
    {
        NSLog(@"用户拒绝");
    }
    else if (status == CNAuthorizationStatusAuthorized)
    {
        NSLog(@"已经授权");
        [self getContact];
    }
    
}

- (void)getContact{
    
    // 获取指定的字段,并不是要获取所有字段,需要指定具体的字段
    CNContactStore *contactStore = [CNContactStore new];
    NSArray *keys = @[CNContactPhoneNumbersKey,CNContactGivenNameKey];
   
    // 获取通讯录中所有的联系人
    CNContactFetchRequest *request = [[CNContactFetchRequest alloc] initWithKeysToFetch:keys];
    
    [contactStore enumerateContactsWithFetchRequest:request error:nil usingBlock:^(CNContact * _Nonnull contact, BOOL * _Nonnull stop) {

        NSString *givenName = contact.givenName;
        NSArray *phoneNumbers = contact.phoneNumbers;
  
        //一个人有多个电话号码
        for (CNLabeledValue *labelValue in phoneNumbers) {
            
            CNPhoneNumber *phoneNumber = labelValue.value;
            
            NSString * string = phoneNumber.stringValue ;
            
            NSLog(@"姓名:%@, 电话号码:%@", givenName, string);
           
        }
        
    }];
    
}

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值