How to share a pdf that is in a webview in Swift

2

I have a webview and I call it an address that if accessed by a browser forces a download of a PDF, in the app I created I loaded the PDF in a webview, but I would also give the user the option to share this PDF by e- mail, send to IcloudDrive, send to Ibook's etc.

func asyncTask(parametros: String, id: String) {

        DispatchQueue.global(qos: DispatchQoS.userInitiated.qosClass).async {

            DispatchQueue.main.async 
                let boletoURL = URL(string: "http://www.meusite/01_2017.pdf")
                print(boletoURL!)
                let boletoURLRequest = URLRequest(url: boletoURL!)
                self.webView.isUserInteractionEnabled = true
                self.webView.loadRequest(boletoURLRequest)
            }
        }
    }
    
asked by anonymous 30.03.2017 / 16:54

2 answers

1

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")
            }
        }
    }
}
    
31.03.2017 / 17:42
0

Hello, for this case use UIActivityViewController :

if  let shareURL = URL(string: "http://www.meusite/01_2017.pdf") {

    var shareItems = [Any]()
    shareItems.append("Compartilhar em...")
    shareItems.append(shareURL)

    let avController = UIActivityViewController(activityItems: shareItems, applicationActivities: nil)
    avController.excludedActivityTypes : [UIActivityType] = [
        .postToWeibo, 
        .message,
        .mail,
        .print,
        .copyToPasteboard,
        .assignToContact,
        .saveToCameraRoll,
        .addToReadingList,
        .postToFlickr,
        .postToVimeo,
        .postToTencentWeibo,
        .airDrop
    ] // caso queira excluir alguma opção

    self.present(avController, animated: true, completion: nil)
}
    
31.03.2017 / 04:30