【问题标题】:List contacts with phone numbers列出带有电话号码的联系人
【发布时间】:2017-01-18 12:08:15
【问题描述】:

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

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

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

【问题讨论】:

  • 到现在为止你尝试了什么?
  • 我尝试了我在代码片段中写的内容。
  • @Eir 试试我的获取联系人列表的代码stackoverflow.com/questions/41719037/…
  • 您是否尝试了以下答案并为您找到了解决方案?
  • 我帮你Eir。告诉你到底想要什么?

标签: ios objective-c contacts


【解决方案1】:
#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];

        }
    }];

【讨论】:

  • 我为这个解决方案添加了一个加号,因为它既漂亮又干净。但是,我没有将其标记为已接受的答案,因为我在提出请求时要求一种方法来排除无电话联系人的获取时间。也许那是不可能的。如果是这样,那将是我问题的正确答案。
  • 尽管在您的代码中,最终结果是您的联系人也没有电话号码。
【解决方案2】:

使用以下方法并导入

#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);
                }

            }
        }
    }];
}

【讨论】:

  • 好吧,这似乎可以获取所有联系人,无论他们是否有电话号码。
【解决方案3】:

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

CNContact 谓词

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

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

另外:

不支持复合谓词。

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

【讨论】:

    猜你喜欢
    • 2014-04-22
    • 1970-01-01
    • 2018-03-26
    • 2015-08-12
    • 2018-01-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-19
    相关资源
    最近更新 更多