Nadia G Nadia G - 11 months ago 62
Swift Question

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.

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( is not a valid email address.

Answer Source

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



if let emailAddress = contactProperty.value as? String {