【问题标题】:swift pdf file not attaching to an emailswift pdf文件未附加到电子邮件
【发布时间】:2016-01-13 16:16:27
【问题描述】:

我有下面的代码,假设附加了一个名为“file.pdf”的文件,该文件是这样创建并放置到临时目录中的

pdfFileUrl = "\(NSTemporaryDirectory())file.pdf" 

但是电子邮件没有我期望的附件

@IBAction func sendEmail(sender: AnyObject) {

    createReportPDF()

    if MFMailComposeViewController.canSendMail() {
        let mail = MFMailComposeViewController()
        mail.mailComposeDelegate = self
        mail.setToRecipients(["dpreston10@gmail.com"])
        mail.setMessageBody("<p>You're so awesome!</p>", isHTML: true)
        if let filePath = NSBundle.mainBundle().pathForResource(pdfFileUrl, ofType: "pdf") {
            print("File path loaded.")

            if let fileData = NSData(contentsOfFile: filePath) {
                print("File data loaded.")
                mail.addAttachmentData(fileData, mimeType: "application/pdf", fileName: "file.pdf")
            }
        }

        presentViewController(mail, animated: true, completion: nil)
    } else {
        // show failure alert
    }
}

【问题讨论】:

  • 就日志输出而言,您看到了什么?我只是想确定逻辑可能在哪里出错。
  • 我的打印语句都没有打印。所以看起来 if let filePath 失败了..不知道为什么
  • 您的pdfFileUrl 是什么格式?你可以在这里打印出来吗?
  • 在模拟器中运行它看起来像这样 /Users/dpreston10/Library/Developer/CoreSimulator/Devices/40DD5B0A-6168-4F2E-A220-D9DEE50FEFDA/data/Containers/Data/Application/C8F3E51D-479D -463B-A7DF-C1CCCB57A970/tmp/file.pdf
  • 如何在应用程序中删除临时文件?随着时间的推移,这种情况会自行发生,还是开发者需要考虑删除?

标签: swift pdf mfmailcomposeviewcontroller


【解决方案1】:

由于您的文件已放入用户的临时文件夹,我认为无法通过 NSBundle 方法访问它。也就是说,如果您将 NSData 写入临时文件夹中的磁盘,然后直接通过电子邮件发送,您可能需要考虑将该变量 (pdfData) 传递给邮件控制器,例如:

mail.addAttachmentData(pdfData, mimeType: "application/pdf", fileName: "file.pdf")

【讨论】:

  • 没有 pdf 文件是作为应用程序的一部分生成的,并且未捆绑。它保存在临时文件夹中。我可以查看 pdf,所以我知道它在那里
  • 能否贴出带有变量pdfFileUrl的代码?
  • 确定是pdfFileUrl = "\(NSTemporaryDirectory())file.pdf" pdfData.writeToFile(pdfFileUrl, atomically: true)
  • 我注释掉了if let filePath = NSBundle.mainBundle().pathForResource(pdfFileUrl, ofType: "pdf") {,它就像一个冠军......很想知道那一行的问题是什么,但我现在继续前进,因为我知道该文件存在于那一点..但仍然
  • 我已经更新了我的解决方案,希望能反映您的 cmets。
猜你喜欢
  • 2020-11-21
  • 2023-03-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-03-14
  • 1970-01-01
相关资源
最近更新 更多