-
-
Save kirsteins/c367f17c54884dee27df to your computer and use it in GitHub Desktop.
Send emails with attachments in iOS using Swift
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// ViewController.swift | |
// SendEmailWithAttachment | |
// | |
// Created by Kelly Egan on 3/17/15. | |
// Copyright (c) 2015 Kelly Egan. All rights reserved. | |
// | |
import UIKit | |
import MessageUI | |
class ViewController: UIViewController, MFMailComposeViewControllerDelegate { | |
@IBOutlet weak var emailButton: UIButton! | |
override func viewDidLoad() { | |
super.viewDidLoad() | |
// Do any additional setup after loading the view, typically from a nib. | |
} | |
override func didReceiveMemoryWarning() { | |
super.didReceiveMemoryWarning() | |
// Dispose of any resources that can be recreated. | |
} | |
@IBAction func sendEmail(sender: UIButton) { | |
//Check to see the device can send email. | |
if( MFMailComposeViewController.canSendMail() ) { | |
println("Can send email.") | |
let mailComposer = MFMailComposeViewController() | |
mailComposer.mailComposeDelegate = self | |
//Set the subject and message of the email | |
mailComposer.setSubject("Have you heard a swift?") | |
mailComposer.setMessageBody("This is what they sound like.", isHTML: false) | |
if let filePath = NSBundle.mainBundle().pathForResource("swifts", ofType: "wav") { | |
println("File path loaded.") | |
if let fileData = NSData(contentsOfFile: filePath) { | |
println("File data loaded.") | |
mailComposer.addAttachmentData(fileData, mimeType: "audio/wav", fileName: "swifts") | |
} | |
} | |
self.presentViewController(mailComposer, animated: true, completion: nil) | |
} | |
} | |
func mailComposeController(controller: MFMailComposeViewController!, didFinishWithResult result: MFMailComposeResult, error: NSError!) { | |
self.dismissViewControllerAnimated(true, completion: nil) | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment