swiftmfmailcomposeviewcontrollermfmailcomposer

Getting email address from the contact details


Im trying to open the MailComposeViewController from the contacts details using swift. Everything works fine, when I click the contact's email, the page opens, but i would like to populate the recipient email field with the email i just clicked, but I don't know how to do it.

Here is my code:

 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")
    }
}

I can only add strings to mail.setToRecipients. When I use contactProperty.value, it gives me this error:

Optional(example@email.com) is not a valid email address.


Solution

  • CNContactProperty.value is of type AnyObject? which means it's an optional.
    So you need to safely unwrap it and cast it as string.

    Try replacing this

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

    with

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