uz7
uz7

Reputation: 159

adding IBAction to send an email from my app

I have a contact us page in my app which shows my Facebook, twitter and website pages. I have managed to get them to work properly by linking a IBAction to the button. The code i used below, however i would like to do the same with my email. When the button is pressed i want to open up the email on the phone and the "To" "subject" fields to be already filled in. I don't want to add a email form to my app as that is the only thing I can find info on. Is there a way i can achieve this?

      import UIKit
       import MessageUI

        class SocialViewController: UIViewController {

override func viewDidLoad() {
    super.viewDidLoad()

    // Do any additional setup after loading the view.
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}



     @IBAction func openWeb(sender: AnyObject) {
UIApplication.sharedApplication().openURL(NSURL(string: "http://www.xxxxxxxxxxxx.com")!)
   }



   @IBAction func openFB(sender: AnyObject) {

if UIApplication.sharedApplication().canOpenURL(NSURL(string: "fb://profile/XXXXXXXX")!) {
  UIApplication.sharedApplication().openURL(NSURL(string: "fb://profile/XXXXXXXXXX")!)
} else {
  UIApplication.sharedApplication().openURL(NSURL(string: "https://facebook.com/XXXXXXXXX")!)
}
  }



  @IBAction func openTW(sender: AnyObject) {

if UIApplication.sharedApplication().canOpenURL(NSURL(string: "tw://profile/XXXXXXXXX")!) {
  UIApplication.sharedApplication().openURL(NSURL(string: "fb://profile/XXXXXXX")!)
} else {
  UIApplication.sharedApplication().openURL(NSURL(string: "https://twitter.com/XXXXXXX")!)
}
  }



    }

Upvotes: 0

Views: 184

Answers (1)

Rashwan L
Rashwan L

Reputation: 38833

To send a mail with Swift through the native mail application add MFMailComposeViewControllerDelegate to your class inheritance

And add the following in your action:

var mail: MFMailComposeViewController!

let toRecipients = ["[email protected]"]
let subject = "Subject"
let body = "Your body text"

mail = MFMailComposeViewController()
mail.mailComposeDelegate = self
mail.setToRecipients(toRecipients)
mail.setSubject(subject)
mail.setMessageBody(body, isHTML: true)

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

Upvotes: 1

Related Questions