MFMailComposeViewControllerを使ってメールを作成します。
まずはMessageUIをインポートします。
import MessageUI
デリゲートを追加します。
class sample: UIViewController, MFMailComposeViewControllerDelegate {
func mail(subject: String, mailbody: String) {
let composeVC = MFMailComposeViewController()
composeVC.mailComposeDelegate = self
composeVC.setToRecipients(["送信先メールアドレス"])
composeVC.setSubject(subject)
composeVC.setMessageBody(mailbody, isHTML: false)
let layer = UIApplication.shared.keyWindow?.layer
let scale = UIScreen.main.scale
UIGraphicsBeginImageContextWithOptions((layer?.frame.size)!, false, scale)
layer?.render(in: UIGraphicsGetCurrentContext()!)
let screenshot = UIGraphicsGetImageFromCurrentImageContext()
let image = UIImageJPEGRepresentation(screenshot!, 1.0)
UIGraphicsEndImageContext()
composeVC.addAttachmentData(image!, mimeType: "image/png", fileName: "screenshot.png")
self.present(composeVC, animated: true, completion: nil)
}
デリゲートで必要なメソッド
メール送信やキャンセルの操作を受けて実行されます。
func mailComposeController(_ controller: MFMailComposeViewController, didFinishWith result: MFMailComposeResult, error: Error?) {
controller.dismiss(animated: true, completion: nil)
switch result {
case .sent: //送信
break
case .saved: //保存
break
case .failed: //失敗
break
case .cancelled: //キャンセル
break
default:
break
}
}
Xcode: 8.3.2
Swift: 3.1
OS: Sierra 10.12