SWIFT 4 UPDATE
1) Add to .plist
<key>NSContactsUsageDescription</key> <string>Our application needs to your contacts</string>
2) Request authorization if you do not have one
func requestAccess() { let store = CNContactStore() store.requestAccess(for: .contacts) { granted, error in guard granted else { DispatchQueue.main.async { self.presentSettingsActionSheet() } return } } } func presentSettingsActionSheet() { let alert = UIAlertController(title: "Permission to Contacts", message: "This app needs access to contacts in order to ...", preferredStyle: .actionSheet) alert.addAction(UIAlertAction(title: "Go to Settings", style: .default) { _ in let url = URL(string: UIApplicationOpenSettingsURLString)! UIApplication.shared.open(url) }) alert.addAction(UIAlertAction(title: "Cancel", style: .cancel)) present(alert, animated: true) }
2) Check the authorization status if you request it earlier
if CNContactStore.authorizationStatus(for: .contacts) == .authorized { getContacts() }
3) Call Get contacts
var contacts = [CNContact]() func getContacts(){ let contactStore = CNContactStore() let keys = [CNContactGivenNameKey, CNContactFamilyNameKey, CNContactPhoneNumbersKey, CNContactImageDataAvailableKey, CNContactThumbnailImageDataKey] let request = CNContactFetchRequest(keysToFetch: keys as [CNKeyDescriptor]) request.sortOrder = CNContactSortOrder.givenName do { try contactStore.enumerateContacts(with: request) { (contact, stop) in self.contacts.append(contact) } } catch { print("unable to fetch contacts") } }
4) THIS IS THE FUNCTION OF OBTAINING A NAME OF CONTACT OR NUMBER
func getNameFromContacts(number: String) -> String { var contactFetched : CNContact var contactName = "" if contacts.count > 0 { let numberToBeCompared = number.components(separatedBy:CharacterSet.decimalDigits.inverted).joined(separator: "") for c in contacts { for n in c.phoneNumbers { if let numberRetrived = n.value as? CNPhoneNumber { let numberRetrivedFixed = numberRetrived.stringValue.components(separatedBy:CharacterSet.decimalDigits.inverted).joined(separator: "") if numberRetrivedFixed.elementsEqual(numberToBeCompared){ contactName = c.givenName
source share