在 Swift 2.0 Contact Framework iOS 中从 CNContactPicker 获取电子邮件地址
Posted
技术标签:
【中文标题】在 Swift 2.0 Contact Framework iOS 中从 CNContactPicker 获取电子邮件地址【英文标题】:Fetch email address from CNContactPicker in Swift 2.0 Contact Framework iOS 【发布时间】:2016-04-12 16:32:05 【问题描述】:我正在尝试从新的联系人框架 ios 9 中获取选择的电子邮件地址,但我找不到正确的解决方案。电话号码和姓名工作正常。
func contactPicker(picker: CNContactPickerViewController, didSelectContactProperty contactProperty: CNContactProperty)
let phoneNumberString: String
let emailString: String
let contact = contactProperty.contact
let contactName = CNContactFormatter.stringFromContact(contact, style: .FullName) ?? ""
let propertyName = CNContact.localizedStringForKey(contactProperty.key)
let message = "Picked \(propertyName) for \(contactName)"
if(propertyName == "Phone")
let phoneNumber = contactProperty.value as! CNPhoneNumber
//print(contact.givenName)
phoneNumberString = phoneNumber.stringValue ?? ""
inputPhone.text = phoneNumberString.regexPatern("[0-9]+").joinWithSeparator(" ")
if(propertyName == "Email")
I need email address //print(email contact)
inputName.text = contact.givenName
inputSurname.text = contact.familyName
// Display only a person's phone, email, and birthdate
let displayedItems = [CNContactPhoneNumbersKey, CNContactEmailAddressesKey, CNContactBirthdayKey]
picker.displayedPropertyKeys = displayedItems
【问题讨论】:
你找到方法了吗? 【参考方案1】:您可以通过以下代码获取邮件 ID:Swift 2.0
@available(iOS 9.0, *)
func contactPicker(picker: CNContactPickerViewController,
didSelectContact contact: CNContact)
if contact.isKeyAvailable(CNContactPhoneNumbersKey)
let con = contact.mutableCopy() as! CNMutableContact
//Email
print(con.emailAddresses[0].valueForKey("labelValuePair")?.valueForKey("value"))
//MobileNo
print(con.phoneNumbers[0].valueForKey("labelValuePair")?.valueForKey("value")?.valueForKey("stringValue"))
else
print("No phone numbers are available")
以下在 Swift 3.0
中运行良好 @available(iOS 9.0, *)
func contactPicker(_ picker: CNContactPickerViewController, didSelect contacts: [CNContact])
if contacts[0].isKeyAvailable(CNContactPhoneNumbersKey)
let con = contacts[0].mutableCopy() as! CNMutableContact
let firstName = con.value(forKey: "givenName") as! String
let lastName = con.value(forKey: "familyName") as! String
let valPairs = (con.phoneNumbers[0].value(forKey: "labelValuePair") as AnyObject)
let value = valPairs.value(forKey: "value") as AnyObject
//Mobile No
print(value.value(forKey: "stringValue"))
//Mail
let mailPair = (con.emailAddresses[0].value(forKey: "labelValuePair") as AnyObject)
print(mailPair.value(forKey: "value"))
else
print("No phone numbers are available")
【讨论】:
以上是关于在 Swift 2.0 Contact Framework iOS 中从 CNContactPicker 获取电子邮件地址的主要内容,如果未能解决你的问题,请参考以下文章
如何在 swift 2.0 中翻译我的硬编码字符串? [复制]
可以应用于每个UITextField的自定义类 - Swift