首页 > 解决方案 > 无论如何,我是否可以在 Swift 中使用 MFMessageComposeViewController() 通过文本发送 PDF 和 PNG?

问题描述

每当我尝试使用 .addAttachmentURL 时,它都不会附加任何内容。ViewController 在文本正文中没有任何内容。URL 是我的文件默认值中 pdf数据的路径(我不知道这是否会有所不同)。有什么方法可以通过这样的文本发送 PDF 吗?通过查看文档或 StackOverflow,我没有找到任何东西。此外,我还没有实现它,但我想知道是否有办法将 PNG 也附加到我与 PDF 一起发送的这条消息中。

func getFileManager() -> NSString {
        let filePath = (NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0] as NSString)
        return filePath
    }


func displayMessageInterface() {
        let composeVC = MFMessageComposeViewController()
        composeVC.messageComposeDelegate = self
        
        // Configure the fields of the interface.
        composeVC.recipients = ["000000000"]
        var url = URL(string: self.getFileManager() as String)!
        url.appendPathComponent("my_report.pdf")
        composeVC.addAttachmentURL(url, withAlternateFilename: 
        "this file")
        
        // Present the view controller modally.
        if MFMessageComposeViewController.canSendText() {
            self.present(composeVC, animated: true, completion: nil)
        } else {
            print("Can't send messages.")
        }
    }

标签: swift

解决方案


您使用了错误的 URL 初始化程序。URL(string:)在这种情况下,初始化程序需要一个方案file://。您需要使用URL(fileURLWithPath:)初始化程序或简单地使用 FileManager urls 方法获取文档目录 URL:

extension URL {
    static let documentDirectory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
}

let url = URL.documentDirectory.appendingPathComponent("my_report.pdf")

当您说“URL 是我的文件默认值中的 pdf 数据的路径”时,我不确定您的意思。如果您已将文件包含在项目 Bundle 中,则需要使用其url(forResource:)方法。

let url = Bundle.main.url(forResource: "my_report", withExtension: "pdf")!

推荐阅读