Saving array into text file and attaching to email in swift
Asked Answered
F

1

6

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?

Folder answered 27/10, 2015 at 3:5 Comment(2)
Have you looked at this? https://mcmap.net/q/715689/-attaching-txt-to-mfmailcomposeviewcontrollerObtrude
I have found some documentation in objective c. But I am trying to perform this in Swift.Folder
F
19

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)
}
Flameproof answered 27/10, 2015 at 3:44 Comment(8)
Animal. Thanks for replying man. I have this current code pastebin.com/wH10RLup it does not show an attachment at all, and I don't think I missed anything. Please take a look. Thanks! Also, the variable I have is already joined with \n lines.Folder
Unfortunately, it isn't. No errors. But nothing attaches.Folder
I updated the answer above a little bit but I have to do a lot of work to really test this. Can you check the value of 'data' and see that it has been written too?Flameproof
I just wanted to know where in the execution you are having problems. Can you set a breakpoint after the data variable is giver a value and check if it really gets any data from the string?Flameproof
i tried to print data and it isn't getting anything.Folder
Let us continue this discussion in chat.Flameproof
This is the correct answer. He is indeed, an Animal!Folder
This got me so close... Note: the optional method for dismissing as changed! It is now, "func mailComposeController(_ controller: MFMailComposeViewController, didFinishWith result: MFMailComposeResult, error: Error?)" The small change is, "didFinishWith" vs "didFinishWithResult" Took me forever to figure this out.. Hope this saves someone else. Otherwise, this answer is spot on!Fiddlededee

© 2022 - 2024 — McMap. All rights reserved.