将数组保存到文本文件中并附加到swift

时间:2015-10-27 03:05:31

标签: ios swift export-to-csv mfmailcomposer

我最近一直在试图将.txt文件创建到电子邮件中。

我有一个变量,它是我要写入txt文件的字符串列表,然后作为附件添加到电子邮件中。

我还没有找到任何体面的文件。

期待一些很好的投入。谢谢!

编辑---------- 我找到了这个代码示例:我收到以下错误。

@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)

我收到错误告诉我“类型'字符串'的值没有成员URLByAppendingPathComponent'”

我该如何解决?

1 个答案:

答案 0 :(得分:15)

用于发送带附件的邮件

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)
    }
}

基于 http://kellyegan.net/sending-files-using-swift/

从数组

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

}

但是,您可以从字符串创建NSData,而不是先将其写入文件。

//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)
    }
}

然后关闭结果

上的作曲家控制器
func mailComposeController(controller: MFMailComposeViewController, didFinishWithResult result: MFMailComposeResult, error: NSError?) {
    controller.dismissViewControllerAnimated(true, completion: nil)
}