Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import ContactsUI
- import UIKit
- class ViewController: UIViewController, CNContactPickerDelegate {
- override func viewDidLoad() {
- super.viewDidLoad()
- openAddressbook(vc: ViewController())
- }
- //MARK:- CNContactPickerDelegate Method
- var contactStore = CNContactStore()
- func requestForAccess(completionHandler: @escaping (_ accessGranted: Bool) -> Void) {
- let authorizationStatus = CNContactStore.authorizationStatus(for: CNEntityType.contacts)
- switch authorizationStatus {
- case .authorized:
- completionHandler(true)
- case .denied, .notDetermined:
- self.contactStore.requestAccess(for: CNEntityType.contacts, completionHandler: { (access, accessError) -> Void in
- if access {
- completionHandler(access)
- }
- else {
- if authorizationStatus == CNAuthorizationStatus.denied {
- let message = "\(accessError!.localizedDescription)\n\nPlease allow the app to access your contacts through the Settings."
- print(message);
- }
- }
- })
- default:
- completionHandler(false)
- }
- }
- func openAddressbook(vc: UIViewController){
- requestForAccess { (accessGranted) in
- if accessGranted == true{
- let cnPicker = CNContactPickerViewController()
- cnPicker.delegate = self
- self.present(cnPicker, animated: true, completion: nil)
- }
- }
- }
- func contactPicker(_ picker: CNContactPickerViewController, didSelect contact: CNContact) {
- if contact.isKeyAvailable(CNContactPhoneNumbersKey){
- // handle the selected contact
- firstNameField.text = contact.givenName
- middleNameField.text = contact.middleName
- lastNameField.text = contact.familyName
- var numberArray = [String]()
- for number in contact.phoneNumbers {
- let phoneNumber = number.value
- numberArray.append(phoneNumber.stringValue)
- }
- if numberArray.count > 0 {
- cellPhoneField.text = numberArray[0]
- if numberArray.count > 1 {
- officeNumberField.text = numberArray[1]
- if numberArray.count > 2 {
- homeNumberField.text = numberArray[2]
- }
- }
- }
- // Set the contact's home email address.
- var homeEmailAddress: String!
- for emailAddress in contact.emailAddresses {
- if emailAddress.label == CNLabelHome {
- homeEmailAddress = emailAddress.value as String
- break
- }
- }
- if homeEmailAddress != nil {
- emailField.text = homeEmailAddress
- }
- if contact.isKeyAvailable(CNContactPostalAddressesKey) {
- if let postalAddress = contact.postalAddresses.first?.value {
- // self.addressStreet.text = CNPostalAddressFormatter().string(from: postalAddress)
- self.addressStreet.text = postalAddress.street
- self.addressCity.text = postalAddress.city
- self.addressZip.text = postalAddress.postalCode
- self.addressState.text = postalAddress.state
- }
- }
- companyCategoryField.text = "PersonalContact"
- companycategory = 3
- }
- }
- func contactPickerDidCancel(picker: CNContactPickerViewController) {
- print("Cancelled picking a contact")
- }
- }
Add Comment
Please, Sign In to add comment