Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR SWIFT

how to send a file from file manager in mail swift

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 = ["a@a.com"]
            //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
        }
}
Source by stackoverflow.com #
 
PREVIOUS NEXT
Tagged: #send #file #file #manager #mail #swift
ADD COMMENT
Topic
Name
9+3 =