从Swift 2.0 Contact Framework iOS中的CNContactPicker获取电子邮件地址

问题描述 投票:1回答:1

我正在尝试从新的联系人框架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

}
ios swift cncontact
1个回答
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")
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.