2016-08-23 194 views
0

我試圖從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 protected])不是有效的電子郵件地址。

+0

使用 '作爲' 替代的地址...中庸分配 –

+0

我怎麼做之前解開呢?對不起,剛剛這個。 – art3mis

回答

1

CNContactProperty.value類型爲AnyObject?這意味着它是可選的。
所以你需要安全地解開它並將其作爲字符串進行投射。

試試這個

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

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

這工作完美,謝謝:) – art3mis

相關問題