Sureshtrb
Sureshtrb

Reputation: 61

Swift pdf attachment in Mail

In my code

class DocViewController: UIViewController,UITextViewDelegate, MFMailComposeViewControllerDelegate{
    var result:String!
    override func viewDidLoad() {
        super.viewDidLoad()
        result = "/Test - " + dateToday!
        func getPDFFileName(_ name: String) -> String {
            let newPDFName = "\(name).pdf"
            let paths = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)
            let documentsDirectory = paths[0]
            let pdfFileName: String = (documentsDirectory as String).appending(newPDFName);
            print(pdfFileName)
            return pdfFileName
        }
        @IBAction func sendMail(_ sender: UIBarButtonItem) {
            let mailComposeViewController = configuredMailComposeViewController()
            if MFMailComposeViewController.canSendMail() {
                self.present(mailComposeViewController, animated: true, completion: nil)
            } else {
                self.showSendMailErrorAlert()
            }
        }
        func configuredMailComposeViewController() -> MFMailComposeViewController {
            let mailComposer:MFMailComposeViewController = MFMailComposeViewController()
            mailComposer.mailComposeDelegate = self
            let recipients = ["[email protected]"]
            //Set the subject and message of the email
            mailComposer.setToRecipients(recipients)
            mailComposer.setSubject("Test")
            mailComposer.setMessageBody("Send Saved PDF File", isHTML: false)

            if let filePath = Bundle.main.path(forResource: getPDFFileName(result), ofType: "pdf") {
                print("File path loaded.")

                if let fileData = NSData(contentsOfFile: filePath) {
                    print("File data loaded.")
                    mailComposer.addAttachmentData(fileData as Data, mimeType: "application/pdf", fileName: "pdf")
                }
                present(mailComposer, animated: true, completion: nil)
            }
            return mailComposer
        }

I am creating pdf and would like to send through mail. Mail works. But the pdf is not attached. If I use simulator the directory is /Users/xxxxxx/Library/Developer/CoreSimulator/Devices/91BD76E3-7BD6-49E9-87E7-63C87BE980EF/data/Containers/Data/Application/16350B51-6898-45AA-BEF3-F0B0E4FF7556/Documents/Test - Monday, 25 December 2017.pdf

if I use iPhone, the save directory is: /var/mobile/Containers/Data/Application/7374E0A1-3E49-494D-B554-1D9C761FC7C1/Documents/Test - Monday, 25 December 2017.pdf and the console message is 2017-12-25 20:36:45.344149+0530 Karma[7690:1157301] [App] if we're in the real pre-commit handler we can't actually add any new fences due to CA restriction when I try to attach mail. Where am I doing wrong? How to specify the same location for the iPhone to attache the created pdf file? Please help.

EDIT: Below code works and attaching the created pdf with mail:

class DocViewController: UIViewController,UITextViewDelegate, MFMailComposeViewControllerDelegate{
    var result:String!
    override func viewDidLoad() {
        super.viewDidLoad()
        result = "/Test - " + dateToday!
        func getPDFFileName(_ name: String) -> String {
            let newPDFName = "\(name).pdf"
            let paths = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)
            let documentsDirectory = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.documentDirectory, FileManager.SearchPathDomainMask.userDomainMask, true)[0] as! String
            let pdfFileName: String = (documentsDirectory as String).appending(newPDFName);
            print(pdfFileName)
            return pdfFileName
        }
        @IBAction func sendMail(_ sender: UIBarButtonItem) {
            let mailComposeViewController = configuredMailComposeViewController()
            if MFMailComposeViewController.canSendMail() {
                present(mailComposeViewController, animated: true, completion: nil)
            } else {
                self.showSendMailErrorAlert()
            }
        }
        func configuredMailComposeViewController() -> MFMailComposeViewController {
            let mailComposer:MFMailComposeViewController = MFMailComposeViewController()
            mailComposer.mailComposeDelegate = self
            let recipients = ["[email protected]"]
            //Set the subject and message of the email
            mailComposer.setToRecipients(recipients)
            mailComposer.setSubject("Test")
            mailComposer.setMessageBody("Send Saved PDF File", isHTML: false)
            let paths = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.documentDirectory, FileManager.SearchPathDomainMask.userDomainMask, true)[0] as! String

            let filePath = getPDFFileName(result)
                print("File path loaded.")

                if let fileData = NSData(contentsOfFile: filePath) {
                    print("File data loaded.")
                    mailComposer.addAttachmentData(fileData as Data, mimeType: "application/pdf", fileName: result)

                self.present(mailComposer, animated: true, completion: nil)
            }
            return mailComposer
        }
}

Upvotes: 1

Views: 1901

Answers (1)

Vishal Vaghasiya
Vishal Vaghasiya

Reputation: 4901

Swift 4.0

try this

    let mailComposer = MFMailComposeViewController()
    mailComposer.mailComposeDelegate = self

    //Set to recipients
    mailComposer.setToRecipients(["your email address heres"])

    //Set the subject
    mailComposer.setSubject("email with document pdf")
    //set mail body
    mailComposer.setMessageBody("This is what they sound like.", isHTML: true)
    if let filePath = Bundle.main.path(forResource: "All_about_tax", ofType: "pdf")
    {
        print("File path loaded.")
        if let fileData = NSData(contentsOfFile: filePath)
        {
            print("File data loaded.")
            mailComposer.addAttachmentData(fileData, mimeType: "application/pdf", fileName: "All_about_tax.pdf")
        }
    }
    //this will compose and present mail to user
    self.present(mailComposer, animated: true, completion: nil)

Upvotes: 1

Related Questions