mail.setToRecipients(

I am trying to mail to mail.setToRecipients("") It is wanting a string.

i would lke to extract and send emails using a var from defaults var. here is my code.




let userName22 = NSUserDefaults.standardUserDefaults().stringForKey("emailname")

/

if MFMailComposeViewController.canSendMail() {

let mail = MFMailComposeViewController()

mail.mailComposeDelegate = self

mail.setToRecipients(userName22) ////// this wants a string. i want to use the userName22 var

mail.setSubject("Your Find " + restaurant.name)

/

mail.navigationBar.tintColor = UIColor(red: 0.0/255.0, green: 116.0/255.0, blue: 119.0/255.0, alpha: 1.0)

presentViewController(mail, animated: true, completion: nil)

} else {

print("Cannot send mail")

/

}

Replies

stringForKey returns an optional. You need to deal with the case where the value is nil, and unwrap it to get the String. I would probably use Swift's guard statement here. Something like


guard MFMailComposeViewController.canSendMail() else {
   print("Cannot send mail")
   return
}
guard let userName = userName22 else {
   print("No user name specified")
   return
}

// Your code that presents the MFMailComposeViewController, using userName rather than userName22


Or you could just stick in a ! and watch your app crash when there's no value available, as so much sample code and bad examples out there seem to do... 😝