You should use the specific apple framework to compose messages called MessageUI. For you to attach a file in email you need to read the data from your pdf and use the addAttachmentData method to attach them to the email. If your file is online you need to download asynchronously using URLSession dataTaskWithURL. If you want to save the file to disk before attaching to email use downloadTaskWithURL:
import MessageUI
class ViewController: UIViewController, MFMailComposeViewControllerDelegate {
@IBOutlet weak var button: UIButton!
@IBAction func compose(_ sender: UIButton) {
if MFMailComposeViewController.canSendMail() {
let mailComposer = MFMailComposeViewController()
mailComposer.mailComposeDelegate = self
mailComposer.setToRecipients(["[email protected]"])
mailComposer.setSubject("Assunto !!!")
mailComposer.setMessageBody("Texto da mensagem", isHTML: false) // texto padrao ou codigo html
// para mandar um arquivo que esta online voce precisa baixar ele antes:
let text = "Se quiser mandar um arquivo de texto por exemplo"
mailComposer.addAttachmentData(Data(text.utf8), mimeType: "text/plain", fileName: "arquivo.txt")
// voce pode enviar mais de um arquivo attached se necessario.
// caso voce precise baixar o arquivo antes eu recomendo URL Session dataTaskWithURL
URLSession.shared.dataTask(with: URL(string:"https://www.domain.com/arquivo.pdf")!) { data, response, error in
guard let data = data, error == nil else {
print(error ?? "nil")
UIApplication.shared.isNetworkActivityIndicatorVisible = false
self.button.isEnabled = true
return
}
print("bytes:", data.count)
mailComposer.addAttachmentData(data, mimeType: "application/pdf", fileName: "arquivo.pdf")
DispatchQueue.main.async {
self.present(mailComposer, animated: true)
}
}.resume()
button.isEnabled = false
UIApplication.shared.isNetworkActivityIndicatorVisible = true
print("download started !!! ao final do download a janela de email sera apresentada !!!")
}
}
func mailComposeController(_ controller: MFMailComposeViewController, didFinishWith result: MFMailComposeResult, error: Error?) {
controller.dismiss(animated: true) {
switch result {
case .cancelled: print("cancelled")
case .saved: print("saved")
case .sent:
let alert = UIAlertController(title: "Mail Composer", message: "Mail was successfully sent", preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "Done", style: .default, handler: nil))
self.present(alert, animated: true)
case .failed: print("failed")
}
}
}
}