从联系人详细信息中获取电子邮件地址

Getting email address from the contact details

我正在尝试使用 swift 从联系人详细信息中打开 MailComposeViewController。一切正常,当我单击联系人的电子邮件时,页面打开,但我想用我刚刚单击的电子邮件填充收件人电子邮件字段,但我不知道该怎么做。

这是我的代码:

 func contactPicker(picker: CNContactPickerViewController, didSelectContactProperty contactProperty: CNContactProperty) {

    if MFMailComposeViewController.canSendMail() {

        let mail = MFMailComposeViewController()

        mail.mailComposeDelegate = self

        //This doesn't work, only asks for a string. 
        mail.setToRecipients(["\(contactProperty.value)"])


        self.dismissViewControllerAnimated(true, completion: {() -> Void in
            self.presentViewController(mail, animated: true, completion: nil)
        })

    } else {
        print("send error")
    }
}

我只能向 mail.setToRecipients 添加字符串。当我使用 contactProperty.value 时,它给我这个错误:

可选(示例@email.com)不是有效的电子邮件地址。

CNContactProperty.valueAnyObject? 类型,这意味着它是可选的。
所以你需要安全地打开它并将其转换为字符串。

尝试替换这个

mail.setToRecipients(["\(contactProperty.value)"])

if let emailAddress = contactProperty.value as? String {
        mail.setToRecipients([emailAddress])
    }