0

Is it possible to fetch a particular contact information or the list of contact informations based on organization name or the job title using both AddressBook and contacts framework ??

Mohamed yaseen
  • 65
  • 1
  • 10

1 Answers1

2

I don't think so you can fetch the contacts from CNContact store by just giving organization name or job title in predicate. You should include organization name and job title in keys to fetch and then iterate the contact list again. Check the code snippet. I hope it helps. Thanks.

func fetchContacts()
{
 let contactStore = CNContactStore()
 var allContainers : [CNContainer] = []
 var allContacts : [CNContact] = []

//you can use one of these/ all keys to filter contacts
 let keysToFetch = [CNContactGivenNameKey, CNContactOrganizationNameKey,   CNContactJobTitleKey]
        var OrganizationArray = [CNContact]()
        do{
            // _______________ Fetch all the Containers_________________________________
            allContainers = try contactStore.containersMatchingPredicate(nil)

        }
        catch{
            print(error)
        }
        for container in allContainers{
            let fetchPredicate = CNContact.predicateForContactsInContainerWithIdentifier(container.identifier)
            do{
                //____________Fetch all the contacts corresponding to every Container______
                let containerResults = try contactStore.unifiedContactsMatchingPredicate(fetchPredicate, keysToFetch: keysToFetch)
               // allContacts.appendContentsOf(containerResults)


                                for contactRec in containerResults {
                                    if contactRec.organizationName != "" {
                                        OrganizationArray.append(contactRec)
                                    }

                                }

            }
            catch{
                print(error)
            }
        }
}
Jush
  • 71
  • 3
  • This i know, i was hoping there will be some other way to fetch a particular contact based on a custom label other then Name properties, If we follow this method we have to iterate through all the contacts available in device to fetch or update a particular contact. – Mohamed yaseen May 24 '16 at 05:09
  • As far as I know, you can fetch contacts based on contact name, contact identifier, container and groups. Apple has not provided predicates for other properties. I think you have to iterate through all the contacts. – Jush May 24 '16 at 05:58
  • Looks like there is no option. – Mohamed yaseen Apr 05 '17 at 06:14