在Swift中将数组保存到文本文件并附加到电子邮件

6

最近我一直在苦苦思索如何将一个 .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")
        }
    }

让路径等于tmpDir.stringByAppendingPathComponent(fileName)

我收到一个错误信息:“'String' 类型的值没有 'URLByAppendingPathComponent' 成员”

如何解决?


你看过这个吗?https://dev59.com/gmUq5IYBdhLWcg3wMNmu#14707748 - Adrian
我在 Objective-C 中找到了一些文档,但我正在尝试使用 Swift 进行操作。 - Danny06191
1个回答

19

发送带附件的邮件

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

很遗憾,它没有任何错误。但是没有任何东西被附加上去。 - Danny06191
我稍微更新了上面的答案,但我需要做很多工作来真正测试这个。你能检查一下“data”的值,并确认它已经被写入了吗? - Moriya
我只是想知道你在执行过程中遇到了什么问题。你能否在数据变量被赋值后设置一个断点,并检查它是否真的从字符串中获取了任何数据? - Moriya
我尝试打印数据,但没有任何输出。 - Danny06191
这是正确的答案。他确实是一只动物! - Danny06191
显示剩余3条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接