用电话号码列出联系人

我想取(在iOS中使用Objective-C)只有具有电话号码的联系人,但我怎么能做到这一点? 我试图在下面的代码中形成谓词,但显然这是行不通的。

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

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

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

使用下面的方法和导入

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

使用下面的代码获取名称和详细信息的联系方式

 #import <AddressBook/ABAddressBook.h> #import <AddressBookUI/AddressBookUI.h> -(NSMutableArray*)fetchContactList{ ABAddressBookRef addressBook = ABAddressBookCreate(); __block BOOL accessGranted = NO; if (&ABAddressBookRequestAccessWithCompletion != NULL) { // We are on iOS 6 dispatch_semaphore_t semaphore = dispatch_semaphore_create(0); ABAddressBookRequestAccessWithCompletion(addressBook, ^(bool granted, CFErrorRef error) { accessGranted = granted; dispatch_semaphore_signal(semaphore); }); dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER); } else { // We are on iOS 5 or Older accessGranted = YES; [self getContactsWithAddressBook:addressBook]; } if (accessGranted) { return [self getContactsWithAddressBook:addressBook]; } return [[NSMutableArray alloc] init]; } // Get the contacts. - (NSMutableArray*)getContactsWithAddressBook:(ABAddressBookRef )addressBook { NSMutableArray *contactList = [[NSMutableArray alloc] init]; CFArrayRef allPeople = ABAddressBookCopyArrayOfAllPeople(addressBook); CFIndex nPeople = ABAddressBookGetPersonCount(addressBook); NSMutableArray *arrWithoutPhoneContact = [[NSMutableArray alloc] init]; for (int i=0;i < nPeople;i++) { NSMutableDictionary *dOfPerson=[NSMutableDictionary dictionary]; ABRecordRef ref = CFArrayGetValueAtIndex(allPeople,i); //For username and surname ABMultiValueRef phones =(__bridge ABMultiValueRef)((__bridge NSString*)ABRecordCopyValue(ref, kABPersonPhoneProperty)); CFStringRef firstName, lastName; firstName = ABRecordCopyValue(ref, kABPersonFirstNameProperty); if (firstName == nil) { firstName = CFStringCreateWithCString (NULL, "", kCFStringEncodingUTF8);; } lastName = ABRecordCopyValue(ref, kABPersonLastNameProperty); if (lastName == nil) { lastName = CFStringCreateWithCString (NULL, "", kCFStringEncodingUTF8);; } [dOfPerson setValue:[NSString stringWithFormat:@"%@", firstName] forKey:@"name"]; //For Email ids ABMutableMultiValueRef eMail = ABRecordCopyValue(ref, kABPersonEmailProperty); if(ABMultiValueGetCount(eMail) > 0) { [dOfPerson setValue:(__bridge NSString *)ABMultiValueCopyValueAtIndex(eMail, 0) forKey:@"email"]; } NSData *imgData = (__bridge NSData *)(ABPersonCopyImageData(ref)); UIImage *imgProfile = [[UIImage alloc] initWithData:imgData]; if (imgProfile != nil) { [dOfPerson setValue:imgProfile forKey:@"image"]; }else{ [dOfPerson setValue:[UIImage imageNamed:@"DefaultProfile"] forKey:@"image"]; } //For Phone number NSString* mobileLabel; if (ABMultiValueGetCount(phones)) { for(CFIndex j = 0; j < ABMultiValueGetCount(phones); j++) { mobileLabel = (__bridge NSString*)ABMultiValueCopyLabelAtIndex(phones, j); if([mobileLabel isEqualToString:(NSString *)kABPersonPhoneMobileLabel]) { [dOfPerson setValue:[Utility cleanedPhoneNumber:(__bridge NSString*)ABMultiValueCopyValueAtIndex(phones, j)] forKey:@"Phone"]; } else if ([mobileLabel isEqualToString:(NSString*)kABPersonPhoneIPhoneLabel]) { [dOfPerson setValue:[Utility cleanedPhoneNumber:(__bridge NSString*)ABMultiValueCopyValueAtIndex(phones, j)] forKey:@"Phone"]; break ; }else{ [dOfPerson setValue:[Utility cleanedPhoneNumber:(__bridge NSString*)ABMultiValueCopyValueAtIndex(phones, j)] forKey:@"Phone"]; } } }else{ NSLog(@"else"); [arrWithoutPhoneContact addObject:[NSString stringWithFormat:@"%d",i]]; } //Contact Id ABRecordID recordID = ABRecordGetRecordID(ref); [dOfPerson setValue:[NSString stringWithFormat:@"%d",recordID] forKey:@"contactId"]; [contactList addObject:dOfPerson]; } NSLog(@"Withot Phone %@", arrWithoutPhoneContact); for (int j = 0; j < arrWithoutPhoneContact.count; j++) { [contactList removeObjectAtIndex:[[arrWithoutPhoneContact objectAtIndex:j] intValue] - j]; } NSLog(@"Contacts = %@",contactList); return contactList; } 

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

CNContact谓词

预测匹配联系人。 您只能将这些谓词与CNContactStore和CNContactFetchRequest一起使用。

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

另外:

复合谓词不受支持。

所以,做这个过滤的唯一方法就是省略向结果数组添加没有电话号码的联系人。 例如,可以在enumerateContactsWithFetchRequest块中完成。