列出带有电话号码的联系人

时间:2017-01-18 12:08:16

标签: ios objective-c contacts

我想(仅在使用Objective-C的iOS中)获取具有电话号码的联系人,但我该怎么做?我试图在下面的代码中形成谓词,但显然这不起作用。

contacts = [contactStore unifiedContactsMatchingPredicate:[NSPredicate predicateWithFormat:@"phoneNumbers <> nil"] keysToFetch:KEYS error:nil];

那么,这样做的正确方法是什么?谢谢你的帮助!

3 个答案:

答案 0 :(得分:2)

#import <Contacts/Contacts.h>


 CNContactStore *store = [[CNContactStore alloc] init];
    [store requestAccessForEntityType:CNEntityTypeContacts completionHandler:^(BOOL granted, NSError * _Nullable error) {
        if (granted == YES) {
            //keys with fetching properties
            NSArray *keys = @[CNContactFamilyNameKey, CNContactGivenNameKey, CNContactPhoneNumbersKey, CNContactImageDataKey, CNContactEmailAddressesKey];
            CNContactFetchRequest *request = [[CNContactFetchRequest alloc] initWithKeysToFetch:keys];
            request.sortOrder = CNContactSortOrderGivenName;
            request.unifyResults = YES;
            NSError *error;

            __block NSString* email;

            BOOL success = [store enumerateContactsWithFetchRequest:request error:&error usingBlock:^(CNContact * __nonnull contact, BOOL * __nonnull stop)
                            {
                                if (error) {
                                    NSLog(@"error fetching contacts %@", error);
                                } else {
                                    NSString *fullName;
                                    NSString* phone;

                                    //                    for (CNContact *contact in cnContacts) {
                                    DeviceContact *aContact = [DeviceContact new];

                                    // copy data to my custom Contacts class.
                                    NSString *firstName = contact.givenName;
                                    NSString *lastName = contact.familyName;

                                    if (lastName == nil) {
                                        fullName=[NSString stringWithFormat:@"%@",firstName];
                                    }else if (firstName == nil){
                                        fullName=[NSString stringWithFormat:@"%@",lastName];
                                    }
                                    else{
                                        fullName=[NSString stringWithFormat:@"%@ %@",firstName,lastName];
                                    }

                                    if ([firstName trim].length > 0) {
                                        aContact.nameForSorting = firstName; // 141116
                                    }else if ([lastName trim].length>0 && aContact.nameForSorting.length<=0) {
                                        aContact.nameForSorting = lastName; // 141116
                                    }

                                    aContact.name = fullName;


                                    if (contact.phoneNumbers!=nil && [contact.phoneNumbers count]>0) {
                                        for (CNLabeledValue *label in contact.phoneNumbers) {
                                            phone =  [CommonUtils removeAllSpecialCharactersFromPhoneNumber:[label.value stringValue]];
                                            if ([phone length] > 0) {
                                                [aContact.phoneNumber addObject:phone];
                                            }
                                        }
                                    }

                                    ////Get all E-Mail addresses from contacts
                                    /// if ([CommonUtils checkIsNullObject:[contact emailAddresses]] && [[contact emailAddresses] count]>0) {
                                    for (CNLabeledValue *label in contact.emailAddresses) {
                                        email = label.value;
                                        if ([email length] > 0)
                                        {
                                            [aContact.email addObject:email];
                                        }
                                    }
                                    // }

                                    // 141116
                                    if ([aContact.name trim].length <= 0) {
                                        if (aContact.email.count>0) {
                                            aContact.name = [aContact.email objectAtIndex:0];
                                        }else if (aContact.phoneNumber.count>0){
                                            aContact.name = [aContact.phoneNumber objectAtIndex:0];
                                        }
                                    }
                                    if ([aContact.nameForSorting trim].length <= 0){
                                        if (aContact.email.count>0) {
                                            aContact.nameForSorting = [aContact.email objectAtIndex:0];
                                        }else if (aContact.phoneNumber.count>0){
                                            aContact.nameForSorting = [aContact.phoneNumber objectAtIndex:0];
                                        }
                                    }

                                    [self.arrAllContacts addObject:aContact];
                                }

                            }];

            if(success){

                dispatch_async(dispatch_get_main_queue(), ^{
                    [CommonUtils hideLoader];

                    completionhandler(self.arrAllContacts);
                });
            }
        }
        else
        {
           // [CommonUtils showAlertMessageWithMessage:@"fdfdggfsgfdgfd" withDelegate:self withCancelTitle:OKAY isOtherButton:NO withOtherButtonTitle:nil withTag:0];
            [CommonUtils hideLoader];

        }
    }];

答案 1 :(得分:0)

使用以下方法并导入

#import <AddressBook/AddressBook.h>
#import <Contacts/Contacts.h> 


-(void)contactsDetailsFromPhoneContactBook{
    CNContactStore *store = [[CNContactStore alloc] init];
    [store requestAccessForEntityType:CNEntityTypeContacts completionHandler:^(BOOL granted, NSError * _Nullable error) {
        if (granted == YES) {
            //keys with fetching properties
            NSArray *keys = @[CNContactFamilyNameKey,CNContactGivenNameKey];
            NSString *containerId = store.defaultContainerIdentifier;
            NSPredicate *predicate = [CNContact predicateForContactsInContainerWithIdentifier:containerId];
            NSError *error;
            NSArray *cnContacts = [store unifiedContactsMatchingPredicate:predicate keysToFetch:keys error:&error];
            if (error) {
                NSLog(@"error fetching contacts %@", error);
            } else {
                NSString *fullName;
                NSString *firstName;
                NSString *lastName;
                for (CNContact *contact in cnContacts) {
                    // copy data to my custom Contacts class.
                    firstName = contact.givenName;
                    lastName = contact.familyName;
                    if (lastName == nil) {
                        fullName=[NSString stringWithFormat:@"%@",firstName];
                    }else if (firstName == nil){
                        fullName=[NSString stringWithFormat:@"%@",lastName];
                    }
                    else{
                        fullName=[NSString stringWithFormat:@"%@ %@",firstName,lastName];
                    }
                    [self.contactsArray addObject:fullName];

                    NSLog(@"working or not %@",self.contactsArray);
                }

            }
        }
    }];
}

答案 2 :(得分:0)

无法过滤掉没有电话号码(或其他属性)的联系人。在我们阅读的文档中:

  

CNContact Predicates

     

谓词匹配联系人。 您只能使用这些谓词   使用CNContactStore和CNContactFetchRequest。

     
      
  • predicateForContactsMatchingName:返回谓词以查找与指定名称匹配的联系人。
  •   
  • predicateForContactsWithIdentifiers:返回谓词以查找与指定标识符匹配的联系人。
  •   
  • predicateForContactsInGroupWithIdentifier:返回谓词以查找指定组中成员的联系人。
  •   
  • predicateForContactsInContainerWithIdentifier:返回谓词以查找指定容器中的联系人。
  •   

另外:

  

不支持复合谓词。

因此,进行过滤的唯一方法是省略向结果数组添加没有电话号码的联系人。例如,可以在enumerateContactsWithFetchRequest

的块中完成