//MARK: Contacts
func checkContactsStatus() {
let status = CNContactStore.authorizationStatus(for: .contacts)
if status == .denied || status == .restricted {
presentSettingsActionSheet()
return
}
}
//Ask for Contact Permissions
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)
}
func contactPicker(_ picker: CNContactPickerViewController,
didSelect contactProperty: CNContactProperty) {
}
func contactPicker(_ picker: CNContactPickerViewController, didSelect contact: CNContact) {
// You can fetch selected name and number in the following way
// user name
let userName:String = contact.givenName
let surName:String = contact.familyName
let fullName:String = userName + " " + surName
print(fullName)
contactTextField.text = fullName
// user phone number
// let userPhoneNumbers:[CNLabeledValue<CNPhoneNumber>] = contact.phoneNumbers
// let firstPhoneNumber:CNPhoneNumber = userPhoneNumbers[0].value
// user phone number string
// let primaryPhoneNumberStr:String = firstPhoneNumber.stringValue
// print(primaryPhoneNumberStr)
}
func contactPickerDidCancel(_ picker: CNContactPickerViewController) {
}
func chooseContact() {
let contactPicker = CNContactPickerViewController()
contactPicker.delegate = self
contactPicker.displayedPropertyKeys =
[CNContactGivenNameKey
, CNContactPhoneNumbersKey]
self.present(contactPicker, animated: true, completion: nil)
}
Info.plist
<key>NSContactsUsageDescription</key>
<string>This app requires contacts access to function properly.</string>