iOS自定义通讯录

最近开发一个关于社交的App需要获取通讯录的信息,由于项目由iOS9开始兼容,所以使用的时候iOS9以后苹果新推出的框架

获取通讯录信息列表

1.获取权限

 CNAuthorizationStatus status = [CNContactStore authorizationStatusForEntityType:CNEntityTypeContacts];
    
    if (status == CNAuthorizationStatusNotDetermined) {
        CNContactStore *contactStore = [[CNContactStore alloc]init];
        [contactStore requestAccessForEntityType:CNEntityTypeContacts completionHandler:^(BOOL granted, NSError * _Nullable error) {
            if (!granted) {
                NSLog(@"授权失败");
            }else{
                NSLog(@"成功授权");
                [self getContactInfo]; //读取数据
            }
        }];
    }else if (status == CNAuthorizationStatusRestricted){
        NSLog(@"用户拒绝授权");
    }else if (status == CNAuthorizationStatusAuthorized){//已经授权
        
        [self getContactInfo];//读取数据
    }

2.读取数据

    NSArray *keysToFetch = @[CNContactGivenNameKey,CNContactFamilyNameKey,CNContactPhoneNumbersKey];
//一个联系人可能存在多个电话和昵称
    CNContactFetchRequest *fetchRequest = [[CNContactFetchRequest alloc]initWithKeysToFetch:keysToFetch];
    CNContactStore *store = [CNContactStore new];
    
    [store enumerateContactsWithFetchRequest:fetchRequest error:nil usingBlock:^(CNContact * _Nonnull contact, BOOL * _Nonnull stop) {
        ContacterModel *model = [ContacterModel new];
        
        NSString *giveName = contact.givenName;
        NSString *familyName = contact.familyName;
        //拼接姓名
        NSString *nameStr = [NSString stringWithFormat:@"%@%@",familyName,giveName];
        
        model.name = nameStr;
    
        
        NSArray *phoneNumbers = contact.phoneNumbers;
        
        for (CNLabeledValue *labelValue in phoneNumbers) {
            //遍历一个人名下的多个电话号码
            CNPhoneNumber *phoneNumber = labelValue.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:@""];
            
            [model.numberArray addObject:string];
            
 
        }
        if (![model.name isEqualToString:@""] && model.numberArray.count >0
            ) {
          [self.dataArray addObject:model];
        }
        
        

    }];

3.数据排序分组

self.sortedDic = [NSMutableDictionary dictionary];
    [self.dataArray enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
       ContacterModel* model = (ContacterModel *)obj;
        NSString *nameIndex = model.nameIndex;
        if (!self.sortedDic[nameIndex]) {
            //如果不存在这个字段,则创建
            [self.sortedDic setValue:[NSMutableArray array] forKey:nameIndex];
  
        }
        [self.sortedDic[nameIndex] addObject:model];
        
    }];
    
    //将字典中的key排序:A-Z
    self.keyArray = [[_sortedDic allKeys] sortedArrayUsingSelector:@selector(compare:)];

关于联系人我使用了一个模型来定义 其中有一个属性是:@property(nonatomic,copy)NSString *nameIndex;
这个属性定义的是联系人名称拼音的首字母

获取姓名拼音的首字母

+(NSString*)getFistLetterFromString:(NSString*)aString{
    if (!aString || [aString isEqualToString:@""]) {
        return @"#";
    }
    NSMutableString *mutableString = [NSMutableString stringWithString:aString];
    
    CFStringTransform((CFMutableStringRef)mutableString, NULL, kCFStringTransformMandarinLatin, false);//转换为拼音
    CFStringTransform((CFMutableStringRef)mutableString, NULL, kCFStringTransformStripDiacritics, false);//去除音标
    
    NSString *pinyinString = [mutableString uppercaseString];
    
    //这里可以考虑多音字的处理(暂未实现)
    
    NSString *firstStr = [pinyinString substringToIndex:1];
    //判断姓名首位是否为大写字母
    NSString *regxA = @"^[A-Z]$";
    NSPredicate *preA = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",regxA];
    
    return [preA evaluateWithObject:firstStr] ? firstStr : @"#";//如果首位不是大写字母开头就设置为#
}

备注

其中获取名字的首字母和数据的分组排序是知识点,部分Api使用较少,想要深入理解的请自行百度

Demo下载

你可能感兴趣的:(iOS自定义通讯录)