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?
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.
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 }()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With