Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CNContact Frame work not fetching all contacts(iCloud,Gmail)

Tags:

Settings>Contacts>Default Account selected as iCloud and saved a new contact.Then changed Default Account as gmail. CNContactStore not fetching the new saved contact.

 CNContactStore *store = [[CNContactStore alloc] init];
[store requestAccessForEntityType:CNEntityTypeContacts completionHandler:^(BOOL granted, NSError * _Nullable error) {
    if (granted == YES)
    {
        NSArray *keys = @[CNContactFamilyNameKey, CNContactGivenNameKey, CNContactPhoneNumbersKey, CNContactImageDataKey,CNContactEmailAddressesKey];
        NSArray * contactContainerArray =  [store containersMatchingPredicate:nil error:nil];
        for(CNContainer * container in contactContainerArray) {
            NSPredicate *predicate = [CNContact predicateForContactsInContainerWithIdentifier:container.identifier];
            NSError *error;
            NSArray *cnContacts = [store unifiedContactsMatchingPredicate:predicate keysToFetch:keys error:&error];
}
like image 439
Hari R Krishna Avatar asked May 25 '17 06:05

Hari R Krishna


1 Answers

If you simply wish to get all unified contacts (Contacts in different accounts that represent the same person may be automatically linked together. Linked contacts are displayed in macOS and iOS apps as unified contacts) the best solution would be below one

 -(void)fetchContacts
  {
      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];
        NSString *containerId = store.defaultContainerIdentifier;
        NSArray * contactContainerArray =  [store containersMatchingPredicate:nil error:nil];
        CNContactFetchRequest * fetchRequest = [[CNContactFetchRequest alloc]initWithKeysToFetch:keys];
        [store enumerateContactsWithFetchRequest:fetchRequest error:nil usingBlock:^(CNContact * _Nonnull contact, BOOL * _Nonnull stop) {

        }];
      }
  }
like image 116
Vaisakh Avatar answered Sep 21 '22 11:09

Vaisakh