0

Goal: implement a sharesheet (UIActivityViewController) that includes Gmail as an option, and sets the recipient and subject

Problem: setting subject works, but setting recipient (forKey: "to") crashes the program.

I would like to have the ability to set the sender and recipient field of the share sheet email client, but so far I have been unable to find any way of doing this. Any help is appreciated!

Relevant code:

let email = ["bob@bobsCompany.com"]
let activityVC = UIActivityViewController(activityItems: [""], applicationActivities: nil)

activityVC.excludedActivityTypes = excludedActivity

activityVC.setValue("Subject Title", forKey: "subject")

activityVC.setValue(email[0], forKey: "to")

activityVC.popoverPresentationController?.sourceView = self.view
self.presentViewController(activityVC, animated: true, completion: nil)
J. doe
  • 3
  • 3
  • See this question http://stackoverflow.com/questions/17020288/how-to-set-mail-subject-in-uiactivityviewcontroller-and-also-twitter-sharing-te Additionally the documentation for UIActivityItemSource https://developer.apple.com/library/ios/documentation/UIKit/Reference/UIActivityItemSource_protocol/#//apple_ref/occ/intfm/UIActivityItemSource/activityViewController:subjectForActivityType: – naomimichiko Aug 16 '16 at 21:50

1 Answers1

3

You can only set the Subject for UIActivityViewController. The program crashes because there is no "to" key. You will have to use the MailMFComposeViewController if you want to set the recipients and sender fields.

    if !MFMailComposeViewController.canSendMail()
    {
      let alertMsg = UIAlertController(title: "Test", message: "Mail services not available.", preferredStyle: UIAlertControllerStyle.Alert)
      alertMsg.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.Default, handler: nil))
      self.presentViewController(alertMsg, animated: true, completion: nil)
    }
    else
    {
      let composeVC = MFMailComposeViewController()
      composeVC.mailComposeDelegate = self

      // Configure the fields of the interface.
      composeVC.setToRecipients(["mail@egmail.com"])
      composeVC.setSubject("Subject)
      composeVC.setMessageBody("Hi.", isHTML: false)

      // Present the view controller modally.
      self.presentViewController(composeVC, animated: true, completion: nil)
    }
Christian Abella
  • 5,747
  • 2
  • 30
  • 42