Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to fetch all contacts record in iOS 9 using Contacts Framework

Most part of AddressBook framework is deprecated in iOS 9. In the new Contacts Framework documentation only shows how to fetch records matches a NSPredicate, but what if I want all the record?

like image 234
Jieyi Hu Avatar asked Sep 19 '15 14:09

Jieyi Hu


People also ask

How do I access my phone contacts in Swift?

Swift 4 and 5. import ContactsUI func phoneNumberWithContryCode() -> [String] { let contacts = PhoneContacts. getContacts() // here calling the getContacts methods var arrPhoneNumbers = [String]() for contact in contacts { for ContctNumVar: CNLabeledValue in contact. phoneNumbers { if let fulMobNumVar = ContctNumVar.


1 Answers

Both other answers do only load contacts from the container with the defaultContainerIdentifier. In a scenario, where the user has more than one container (i.e. an Exchange and an iCloud account which both are used to store contacts), this would only load the contacts from the account that is configured as the default. Therefore, it would not load all contacts as requested by the author of the question.

What you'll probably want to do instead is getting all the containers and iterate over them to extract all contacts from each of them. The following code snippet is an example of how we do it in one of our apps (in Swift):

lazy var contacts: [CNContact] = {     let contactStore = CNContactStore()     let keysToFetch = [         CNContactFormatter.descriptorForRequiredKeysForStyle(.FullName),         CNContactEmailAddressesKey,         CNContactPhoneNumbersKey,         CNContactImageDataAvailableKey,         CNContactThumbnailImageDataKey]      // Get all the containers     var allContainers: [CNContainer] = []     do {         allContainers = try contactStore.containersMatchingPredicate(nil)     } catch {         print("Error fetching containers")     }      var results: [CNContact] = []      // Iterate all containers and append their contacts to our results array     for container in allContainers {         let fetchPredicate = CNContact.predicateForContactsInContainerWithIdentifier(container.identifier)          do {             let containerResults = try contactStore.unifiedContactsMatchingPredicate(fetchPredicate, keysToFetch: keysToFetch)             results.appendContentsOf(containerResults)         } catch {             print("Error fetching results for container")         }     }      return results }() 
like image 124
flohei Avatar answered Sep 20 '22 05:09

flohei