我正在用 Xcode 8 和 swift 3 编写一个应用程序,我想在其中提取街道、城市、州、国家和邮政编码的邮政地址详细信息,并将它们填充到视图控制器上的标签中。我已经修改了允许授权的 info.plist 文件,并在下面编写了以下代码。我创建了一个标签来保存信息以及一个按钮来访问联系人。
我能够获取填充到标签中的联系人的全名和电子邮件地址,但我无法弄清楚如何从邮政地址获取地址详细信息,例如街道地址、城市、州、邮政编码和国家/地区。我已经在 Stack Overflow 和互联网上用尽搜索无济于事。我恭敬地请求您的帮助。
任何见解和建议都将受到欢迎。
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)
}
}