如何使用 Swift 在电子邮件中发送附件?


若要使用我们的应用程序从我们的 iPhone 设备发送电子邮件,我们需要导入 iOS SDK 的 MessageUI 框架。在您的应用程序中导入框架后,将一个按钮拖放到视图控制器中。为此按钮添加空操作。

现在在您的视图控制器中添加以下代码。

funccomposeEmail(to email: String,subject: String,Body: String) {
   if( MFMailComposeViewController.canSendMail()) {
      letmailComposer = MFMailComposeViewController()
      mailComposer.mailComposeDelegate = self
      mailComposer.setToRecipients([email])
      mailComposer.setSubject(subject)
      mailComposer.setMessageBody(Body, isHTML: true)
      letpathPDF = "\(NSTemporaryDirectory())result.pdf"
      if let fileData = NSData(contentsOfFile: pathPDF) {
         mailComposer.addAttachmentData(fileData as Data, mimeType: "application/pdf", fileName: "result.pdf")
      }
      self.present(mailComposer, animated: true, completion: nil)
      } else {
         print("email is not supported")
      }
   }
   funcmailComposeController(_ didFinishWithcontroller:
   MFMailComposeViewController, didFinishWith result:
   MFMailComposeResult, error: Error?) {
      self.dismiss(animated: true, completion: nil)
   }
}

在您刚刚创建的按钮的操作中调用此方法。

@IBActionfuncactionButtonOne(_ sender: Any) {
composeEmail(to: "ashish@xy.com", subject: "Saying Hi", Body: "Hey there, hope you are doing well.")
}

当我们运行上述代码并按我们添加的按钮时,我们会得到以下结果。

以下几点需要注意 -

  • 确保在您的 iPhone 上的邮件应用程序中至少添加了一个帐户。

  • 确保您已将 pdf 本地存储在地址中,以便上传。

更新时间: 2020 年 6 月 30 日

498 次浏览

启动你的 职业生涯

通过完成课程获得认证

开始学习
广告
© . All rights reserved.