美文网首页
objectc 通-讯-录

objectc 通-讯-录

作者: 喵喵粉 | 来源:发表于2021-04-01 16:25 被阅读0次
  • 三方库 https://github.com/RITL/RITLContactManager

  • 注意点
    iOS 13中将禁止应用开发者访问用户通讯录备注信息,所以在获取通讯录的keys中不能有下面的这个属性
    CNContactNoteKey
    block线程切换

  1. 请求授权
#import <Contacts/Contacts.h>

///通讯录授权
- (void)contactAuth {
    CNAuthorizationStatus status = [CNContactStore authorizationStatusForEntityType:CNEntityTypeContacts];
    CNContactStore *contactStore = [[CNContactStore alloc] init];
    NSLog(@"status: %ld", (long)status);

    switch (status) {
        case CNAuthorizationStatusNotDetermined:
            [contactStore requestAccessForEntityType:CNEntityTypeContacts completionHandler:^(BOOL granted, NSError *error) {
                NSLog(@"granted:%d error:%@", granted, error.description);
            }];
            break;
        case CNAuthorizationStatusRestricted:
            NSLog(@"访问通讯录受限");
            break;
        case CNAuthorizationStatusDenied:
            NSLog(@"拒绝访问通讯录");
            break;
        case CNAuthorizationStatusAuthorized:
            NSLog(@"已授权");
            break;
        default:
            break;
    }
}
  1. 获取通讯录
- (void)getAllContacts {
    CNAuthorizationStatus status = [CNContactStore authorizationStatusForEntityType:CNEntityTypeContacts];
    if (CNAuthorizationStatusAuthorized != status) {
        NSLog(@"未授权,不能访问通讯录");
        return;
    }
    
    // 获取指定的字段,并不是要获取所有字段,需要指定具体的字段
    NSArray *keysToFetch = @[CNContactGivenNameKey, CNContactFamilyNameKey, CNContactNicknameKey, CNContactPhoneNumbersKey];
    keysToFetch = [self contactAllKeysWithoutNoteKey];
    
    CNContactFetchRequest *fetchRequest = [[CNContactFetchRequest alloc] initWithKeysToFetch:keysToFetch];
    CNContactStore *contactStore = [[CNContactStore alloc] init];
    
    [contactStore enumerateContactsWithFetchRequest:fetchRequest error:nil usingBlock:^(CNContact * _Nonnull contact, BOOL * _Nonnull stop) {
        NSLog(@"-------------------------------------------------------");
        
        //姓名
        NSString *givenName = contact.givenName;
        NSString *familyName = contact.familyName;
        NSString *nickName = contact.nickname;
        NSLog(@"name:%@%@, nickName:%@", familyName, givenName, nickName);

        //电话☎️
        NSArray<CNLabeledValue<CNPhoneNumber *> *> *phoneNumbers = contact.phoneNumbers;
        
        for (CNLabeledValue<CNPhoneNumber *> *phoneNumV in phoneNumbers) {
            //NSString *label = labelValue.label;
            CNPhoneNumber *phoneNumber = phoneNumV.value;
            NSString *string = phoneNumber.stringValue;
            
            //去掉电话中的特殊字符
            string = [string stringByReplacingOccurrencesOfString:@"+86" withString:@""];
            string = [string stringByReplacingOccurrencesOfString:@"-" withString:@""];
            string = [string stringByReplacingOccurrencesOfString:@"(" withString:@""];
            string = [string stringByReplacingOccurrencesOfString:@")" withString:@""];
            string = [string stringByReplacingOccurrencesOfString:@" " withString:@""];
            string = [string stringByReplacingOccurrencesOfString:@" " withString:@""];
            NSLog(@"phone:%@", string);
        }
        
        //邮箱📮
        NSArray<CNLabeledValue<NSString *> *> *emailAddrs = contact.emailAddresses;
        for (CNLabeledValue<NSString *> *emailV in emailAddrs) {
            NSString *label = emailV.label;
            NSString *email = emailV.value;
            NSLog(@"邮箱📮:%@ - %@", label, email);
        }
        
        //住宅🏠
        NSArray<CNLabeledValue<CNPostalAddress *> *> *postalAddrs = contact.postalAddresses;
        for (CNLabeledValue<CNPostalAddress *> *postalAddrV in postalAddrs) {
            CNPostalAddress *addr = postalAddrV.value;
            NSArray *addrStrs = @[addr.street, addr.subLocality, addr.city, addr.subAdministrativeArea, addr.state, addr.country];
            NSLog(@"住宅🏠:%@", [addrStrs componentsJoinedByString:@" "]);
        }
        
    }];
}

返回需要获取的字段

- (NSArray<id<CNKeyDescriptor>> *)contactAllKeysWithoutNoteKey {
    return @[
#if __IPHONE_OS_VERSION_MIN_REQUIRED >= 100000
        CNContactPhoneticOrganizationNameKey,
#endif
        //identifier
        CNContactIdentifierKey,
        
        //name
        CNContactNamePrefixKey,
        CNContactGivenNameKey,
        CNContactMiddleNameKey,
        CNContactFamilyNameKey,
        CNContactPreviousFamilyNameKey,
        CNContactNameSuffixKey,
        CNContactNicknameKey,
        
        //phonetic
        CNContactPhoneticGivenNameKey,
        CNContactPhoneticMiddleNameKey,
        CNContactPhoneticFamilyNameKey,
        
        //number
        CNContactPhoneNumbersKey,
        
        //email
        CNContactEmailAddressesKey,
        
        //postal
        CNContactPostalAddressesKey,
        
        //job
        CNContactJobTitleKey,
        CNContactDepartmentNameKey,
        CNContactOrganizationNameKey,
        
        //note iOS 13中将禁止应用开发者访问用户通讯录备注信息,所以在获取通讯录的keys中不能有下面的这个属性
        //CNContactNoteKey,
        
        //type
        CNContactTypeKey,
        
        //birthday
        CNContactBirthdayKey,
        CNContactNonGregorianBirthdayKey,
        
        //instantMessageAddresses
        CNContactInstantMessageAddressesKey,
        
        //relation
        CNContactRelationsKey,
        
        //SocialProfiles
        CNContactSocialProfilesKey,
        
        //Dates
        CNContactDatesKey
    ];
}

使用第三方库Demo

添加了RITLContactAllKeysWithoutNoteKey方法,只去掉了CNContactNoteKey

        //note
        //CNContactNoteKey,
#import "RITLContactsManager.h"
#import "RITLContactObject.h"
#import "NSString+RITLContactFile.h"

- (void)goRITLContactDemo {
    RITLContactsManager *contactMgr = [RITLContactsManager new];
    contactMgr.descriptors = [NSString RITLContactAllKeysWithoutNoteKey];
    
    dispatch_semaphore_t semaphore = dispatch_semaphore_create(0);
    
    dispatch_async(dispatch_get_global_queue(0, 0), ^{

        __block NSArray<RITLContactObject *> *contactObjs = @[];
        
        //通讯发生变化进行的回调
        contactMgr.contactDidChange = ^(NSArray <RITLContactObject *>* contacts) {
        };
        
        //开始请求
        [contactMgr requestContactsComplete:^(NSArray<RITLContactObject *> *contacts) {
            NSLog(@"read all");
            contactObjs = contacts;
            
            dispatch_semaphore_signal(semaphore);
        } defendBlock:^{
            NSLog(@"not allow");
            
            dispatch_semaphore_signal(semaphore);
        }];
        
        dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
        
        NSLog(@"read all after");

        //打印
        for (RITLContactObject *contact in contactObjs) {
            NSLog(@"%@ %@ %@ %@", contact.nameObject.name, contact.nameObject.givenName, contact.nameObject.familyName, contact.nameObject.nickName);
            
            for (RITLContactPhoneObject *phoneObj in contact.phoneObject) {
                NSLog(@"phone %@ %@", phoneObj.phoneTitle, phoneObj.phoneNumber);
            }
            NSLog(@"---\n");
        }
    });
}

相关文章

  • objectc 通-讯-录

    三方库 https://github.com/RITL/RITLContactManager[https://gi...

  • 实验三通讯录

    1、设计并实现日常生活中通讯录的管理系统。该系统需3位同学一组,按模块分工协作完成,系统具体功能需求描述如下: ①...

  • 防爆通讯录

    讯盾通讯录防护官方网址电脑网址 讯盾通讯录防护手机网址手机网址

  • 5月再见

    #May!goodbye.四月、五月通讯录里新增了不能更新动态的好友[流泪][流泪][流泪] 关于友情,随缘惜缘不...

  • 从今天起,每天跟一个朋友聊聊天

    286位通讯录联系人 574位微信好友 69位社团同事 32位同班同学,3位舍友 … ▼ “朋友很多,能聊很少” ...

  • ObjectC-C简介理解(极客班)

    1,ObjectC是C的拓展; 2,编译ObjectC的工具有三种; 3,通用编译工具GCC ;苹果的编译工具Cl...

  • 常见的工业协议对比、PID、微分与积分区别

    每个仪表都有自己独特的通讯协议,常见的有modbus通讯协议 、RS-232通讯协议、RS-485通讯协议 、HA...

  • ObjectC 上手

    本文结构 参考孟岩老师的文章,对本文结构如下划分 基本数据类型基本语法数组和其他集合类基本输入输出和文件处理,输入...

  • objectc -- 概论

    背景 object graph: 对象图,相比于反映类际关系的UML,对象图用于反映某一时间点各对象之间的相互联系...

  • 本特利3500/92通讯网关产品介绍

    本特利3500/92通讯网关产品介绍 本特利3500/92通讯网关具有广泛的通讯能力,可通过以太网TCP/IP和串...

网友评论

      本文标题:objectc 通-讯-录

      本文链接:https://www.haomeiwen.com/subject/hlvtkltx.html