objectc 通-讯-录

2021-04-01  本文已影响0人  喵喵粉
  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");
        }
    });
}
上一篇 下一篇

猜你喜欢

热点阅读