如何快速将pdf文件上传到电子邮件

时间:2019-07-18 16:17:04

标签: swift

我希望通过单击上传按钮并输入收件人的电子邮件来上传pdf文件,然后将其发送给他/她。单击上传按钮后,它将提示pdf文件内容进行检查,然后再将其发送到接收器。我该如何编码?

@objc func sendMail() {
    if( MFMailComposeViewController.canSendMail() )

    {
        print("Can send email.")

        let mailComposer = MFMailComposeViewController()
        mailComposer.mailComposeDelegate = self

        //Set to recipients
        mailComposer.setToRecipients(["yakupad@yandex.com"])

        //Set the subject
        mailComposer.setSubject("email with document pdf")

        //set mail body
        mailComposer.setMessageBody("This is what they sound like.", isHTML: true)
        let pathPDF = "\(NSTemporaryDirectory())contract.pdf"
        if let fileData = NSData(contentsOfFile: pathPDF)
        {
            print("File data loaded.")
            mailComposer.addAttachmentData(fileData as Data, mimeType: "application/pdf", fileName: "contract.pdf")
        }

        //this will compose and present mail to user
        self.present(mailComposer, animated: true, completion: nil)
    }
    else
    {
        print("email is not supported")
    }

    func mailComposeController(_ didFinishWithcontroller: MFMailComposeViewController, didFinishWith result: MFMailComposeResult, error: Error?)
    {
        self.dismiss(animated: true, completion: nil)
    }

}

1 个答案:

答案 0 :(得分:0)

在这个例子中,我可以共享一个pdf文件,首先您可以看到它,我的意思是,您应该按下“创建pdf文件”按钮,然后您就可以与电子邮件或其他任何内容共享它了。

let appDelegate = UIApplication.shared.delegate as! AppDelegate
documentsURL.appendPathComponent("recibo.pdf")
do {
    try convertedData.write(to: documentsURL)
    let fileManager = FileManager.default
    let docsurl = try! fileManager.url(for:.documentDirectory, in: .userDomainMask, appropriateFor: nil, create: false)
    let documentoPath =  docsurl.appendingPathComponent("recibo.pdf")
    let pdfData = NSData(contentsOf: documentoPath)
    let activityViewController = UIActivityViewController(activityItems: [pdfData!], applicationActivities: nil)
    activityViewController.popoverPresentationController?.sourceView = self.appDelegate.window?.rootViewController?.view
    appDelegate.window?.rootViewController?.present(activityViewController, animated: true) {() -> Void in }
} catch {
    print("the pdf can't be created")
}

您可以为电子邮件变量自定义活动视图控制器