我正在使用 XLS 作为附件在 Swift 3.0 (Xcode 8.2.1) 中处理 MFMailComposeViewController
。我在缓存目录中保存了一个 excel 文件,并为电子邮件的附件检索了该文件。 (见下面的代码)
当我调试代码时,我看到它打印“文件数据已加载。”,这意味着有数据来自沙箱(缓存)。不确定,此 MIME 类型是否正确 "application/vnd.ms-excel"
?
给我奇怪的!我没有看到邮件正文和附件。你能帮忙吗?
到目前为止,这是我的代码:
import MessageUI
class ViewController:MFMailComposeViewControllerDelegate {
func shareFileViaEmail() {
if MFMailComposeViewController.canSendMail() {
let mailComposerVC = MFMailComposeViewController()
mailComposerVC.mailComposeDelegate = self
let paths: [Any] = NSSearchPathForDirectoriesInDomains(.cachesDirectory, .userDomainMask, true)
let documentsDirectory: String = paths[0] as! String
let dataPath: URL = URL(fileURLWithPath: documentsDirectory).appendingPathComponent("record.xls").absoluteURL
if let fileData = NSData(contentsOf: dataPath) {
print("File data loaded.")
mailComposerVC.addAttachmentData(fileData as Data, mimeType: "application/vnd.ms-excel", fileName: "Report")
}
mailComposerVC.setSubject("Report")
mailComposerVC.setMessageBody("Message body", isHTML: false)
self.present(mailComposerVC, animated: true, completion: nil)
}else{
print("Your device could not send e-mail. Please check e-mail configuration and try again.")
}
}
func mailComposeController(_ controller:MFMailComposeViewController, didFinishWith result:MFMailComposeResult, error:Error?) {
self.dismiss(animated: false, completion: nil)
}
}
我在设备中看到以下输出:(无附件和无电子邮件正文)
最佳答案
下面的代码适合我。
if( MFMailComposeViewController.canSendMail() ) {
let mailComposer = MFMailComposeViewController()
mailComposer.mailComposeDelegate = self
//Set the subject and message of the email
mailComposer.setSubject("swift")
mailComposer.setMessageBody("Testing", isHTML: false)
let path = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0] as String
let url = NSURL(fileURLWithPath: path)
let filePath = url.appendingPathComponent("nameOfFileHere")?.path
let fileManager = FileManager.default
if fileManager.fileExists(atPath: filePath!) {
if let fileData = NSData(contentsOfFile: filePath!) {
print("File data loaded.")
mailComposer.addAttachmentData(fileData as Data, mimeType: "application/vnd.ms-excel", fileName: "nameOfFileHere")
}
} else {
print("FILE NOT AVAILABLE")
}
self.present(mailComposer, animated: true, completion: nil)
}
关于ios - 带有 XLS 附件的 Swift MFMailComposeViewController,未找到附件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41932589/