iosswiftexport-to-csvmfmailcomposer

Saving array into text file and attaching to email in swift


I have been pulling my hair out lately trying to create a .txt file into an email.

I have a variable which is a list of strings that I want to write to a txt file, and then add as an attachment to an email.

I have not been able to find any decent documentation on this.

Looking forward to some great input. Thank you!

Edit---------- I found this code sample: and I am getting the following error.

@IBAction func createFile(sender: AnyObject) {
        let path = tmpDir.stringByAppendingPathComponent(fileName)
        let contentsOfFile = "Sample Text"
        var error: NSError?

        // Write File
        if contentsOfFile.writeToFile(path, atomically: true, encoding: NSUTF8StringEncoding, error: &error) == false {
            if let errorMessage = error {
                println("Failed to create file")
                println("\(errorMessage)")
            }
        } else {
            println("File sample.txt created at tmp directory")
        }
    }

let path = tmpDir.stringByAppendingPathComponent(fileName)

I am getting an error telling me "Value of type 'String' has no member URLByAppendingPathComponent' "

How do I fix that?


Solution

  • For sending mail with attachment

    import MessageUI
    
    
    @IBAction func sendEmail(sender: UIButton) {
    
        if( MFMailComposeViewController.canSendMail() ) {
    let mailComposer = MFMailComposeViewController()
                mailComposer.mailComposeDelegate = self
    
                //Set the subject and message of the email
                mailComposer.setSubject("Subject")
                mailComposer.setMessageBody("body text", isHTML: false)
    
                if let fileData = NSData(contentsOfFile: filePath) {
                    mailComposer.addAttachmentData(fileData, mimeType: "text/txt", fileName: "data")
                }
    
                self.presentViewController(mailComposer, animated: true, completion: nil)
        }
    }
    

    based on http://kellyegan.net/sending-files-using-swift/

    Create the file from array

    let strings = ["a","b"]
    let joinedString = strings.joinWithSeparator("\n")
    do {
        try joinedString.writeToFile(path, atomically: true, encoding: NSUTF8StringEncoding)
    } catch {
    
    }
    

    You can however create the NSData from the string instead of first writing it to file.

    //example data
    let filename = "testfile"
    let strings = ["a","b"]
    
    if(MFMailComposeViewController.canSendMail()){
    
        let mailComposer = MFMailComposeViewController()
        mailComposer.mailComposeDelegate = self
        mailComposer.setToRecipients([mail])
        mailComposer.setSubject("\(subject)" )
        mailComposer.setMessageBody("\(messagebody)", isHTML: false)
    
        let joinedString = strings.joinWithSeparator("\n")
        print(joinedString)
        if let data = (joinedString as NSString).dataUsingEncoding(NSUTF8StringEncoding){
            //Attach File
            mailComposer.addAttachmentData(data, mimeType: "text/plain", fileName: "test")
            self.presentViewController(mailComposer, animated: true, completion: nil)
        }
    }
    

    And then dismiss the composer controller on a result

    func mailComposeController(controller: MFMailComposeViewController, didFinishWithResult result: MFMailComposeResult, error: NSError?) {
        controller.dismissViewControllerAnimated(true, completion: nil)
    }