从SWIFT 2.0 Contact Framework IOS中的CNContactPicker获取电子邮件地址

时间:2016-04-12 16:32:06

标签: ios swift cncontact

我试图从新的联系框架IOS9中获取已选择的电子邮件地址,但我找不到正确的解决方案。电话号码和姓名工作正常可以帮助我吗?

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 个答案:

答案 0 :(得分: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")
    }
}