如何从iPhone目录swift附加文件到邮件

时间:2015-07-31 10:00:17

标签: iphone swift email

我是iOS开发的新手

是否可以使用swift将iPhone / iPad设备文件夹中的文件附加到邮件编辑器?我已经制作了一个邮件作曲家,我们可以在那里添加附件。我的问题是我们如何从设备的内存中选择和添加附件?任何帮助表示赞赏 在此先感谢

1 个答案:

答案 0 :(得分:0)

试试这个,

func sendMailWithFile(filePath: String) {

  if MFMailComposeViewController.canSendMail() {
    let composer = MFMailComposeViewController()
    composer.setToRecipients(["mailid"])
    composer.setMessageBody("Body", isHTML: false)
    composer.setSubject("Subject")
    let attachmentData = NSData(contentsOfFile: filePath)
    let mimetype = self.mimeTypefrom(filePath)
    composer.addAttachmentData(attachmentData!, mimeType: mimetype, fileName: filePath.lastPathComponent)
    self.presentViewController(composer, animated: true, completion: nil)
  } else {
    let sendMailErrorAlert = UIAlertView(title: "Could Not Send Email", message: "Check your mail configurations", delegate: self, cancelButtonTitle: "OK")
    sendMailErrorAlert.show()
  } 
} 

func mimeTypefrom(filePath: String) -> String {

    let fileExtension = filePath.pathExtension;
    let UTI =  UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension, fileExtension, nil)
    let mimeType = UTTypeCopyPreferredTagWithClass(UTI!.takeUnretainedValue(), kUTTagClassMIMEType);
    return (mimeType?.takeRetainedValue())! as String
}

注意: nill检查没有选项。

编辑:已添加方法mimeTypefrom