如何使用 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 次瀏覽

啟動你的 職業生涯

透過完成課程獲得認證

開始學習
廣告