iosswiftcontacts-framework

Getting street, city, state, zip and country from contact details in iOS and populating to a label


I am writing an app in Xcode 8 and swift 3 in which I want to extract the postal address details of street, city, state, country and zip code and populate them into a label on a view controller. I have modified the info.plist file allowing authorization and I haver written the following code below.I created a label to hold the information as well as a button to access the contacts.

I am able to get the full name and email address for the contact populated into the label, but I cannot figure out how to get the address details such as street address , city, state, zip code, and country from the postal address. I have exhausted searches on Stack Overflow and the internet to no avail. I am respectfully requesting your assistance.

Any insights and suggestions would be most welcome.

import UIKit
import Contacts
import ContactsUI

class ThirdViewController: UIViewController, CNContactPickerDelegate {
    @IBOutlet weak var lblDetails: UILabel!
    @IBOutlet weak var backTextField: UITextView!

    @IBAction func btnSelectContact(_ sender: Any) {
        let entityType = CNEntityType.contacts
        let authStatus = CNContactStore.authorizationStatus(for:entityType)

        if authStatus == CNAuthorizationStatus.notDetermined {
            let contactStore = CNContactStore.init()
            contactStore.requestAccess(for: entityType, completionHandler:     {(success, nil) in
                if success {
                    self.openContacts()
                }
                else {
                    print("not authorized")
                }
            })
        }
        else if authStatus == CNAuthorizationStatus.authorized {
            self.openContacts()
        }
    }

    func openContacts() {
        let contactPicker = CNContactPickerViewController.init()
        contactPicker.delegate = self as CNContactPickerDelegate
        self.present(contactPicker, animated: true, completion: nil)
    }

    func contactPickerDidCancel(_picker: CNContactPickerViewController) {
        _picker.dismiss(animated: true) {
        }
    }

    func contactPicker(_ picker: CNContactPickerViewController, didSelect contact: CNContact) {
        // when a contact is selected get the full name
        let fullName = "\(contact.givenName) \(contact.familyName)"

        // the following gets the email address from contact
        var email = "No Email Address Found"
        if !contact.emailAddresses.isEmpty {
            let emailString = (((contact.emailAddresses[0] as AnyObject).value(forKey: "labelValuePair")
                as AnyObject).value(forKey: "value"))
            email = emailString! as! String
        }

        // start of adding postaladdresses
        var streetAddress = "No Postal Address Found"
        if !contact.postalAddresses.isEmpty {
            let streetAddressString = (((contact.postalAddresses[0] as AnyObject).value(forKey: "labelValuePair")
                as AnyObject).value(forKey: "value"))
            streetAddress = streetAddressString! as! String
        }

        // end of postal addresses

        // the following takes the information and populates a label on the view controller
        self.lblDetails.text = "\(fullName)\n\(email)\n\(streetAddress)"      //    \n\(streetName)
    }
}

Solution

  • You have to use like this:

    if let addressString = (((contact.postalAddresses[0] as AnyObject).value(forKey: "labelValuePair") as AnyObject).value(forKey: "value")) as? CNPostalAddress {
        let mailAddress = CNPostalAddressFormatter.string(from:addressString, style: .mailingAddress)
        streetAddress = "\(addressString.street), \(addressString.city), \(addressString.state), \(addressString.postalCode), \(addressString.country)"
        streetAddress = "\(mailAddress)
    }
    

    You can get address like this :

    streetAddress = "\(addressString.street), \(addressString.city), \(addressString.state), \(addressString.postalCode), \(addressString.country)"
    

    Or you can get mailing address like this:

    let mailAddress = CNPostalAddressFormatter.string(from:addressString, style: .mailingAddress)
    streetAddress = "\(mailAddress)