I am using wkWebView to load research papers published on IEEE, Science Direct, etc. so when I click on any PDF in the research papers, PDF gets loaded into webview, so is there a way to detect and enable a download icon in wkWebView.
Tried Solution:
I have tried to get the pdf from URLs via URLSession and this is working for like 95% of the times but sometimes I don't get the content of PDF via URLSession and pdf gets loaded into webview because of dynamic URL/PDF creation.
In research, I came across: Get already loaded PDF directly from WKWebView without downloading again But in my case first I need to check if the loaded content is PDF.
A relevant question: add download button for pdf in wkwebview in swift 4 But no answer!!!
To test: open URL: https://www.sciencedirect.com/science/article/pii/S0946672X17308763 in wkWebView and click on the "Download PDF" button this will load the pdf into webview.
In short: Any way to detect if the loaded content is PDF and give a download button to download the pdf content into the documents folder.
Any help appreciated...Thanks
You can detect if the content of the current page is a PDF by checking its mime/content type via the DOM Document.contentType API. If it's application/pdf, we know the web view is currently displaying a PDF, and can show a download button:
func isCurrentDocumentPDF(_ onCompletion: (Bool) -> Void) {
webView.evaluateJavascript("document.contentType") {
_, result in
if let contentType = result as? String, contentType == "application/pdf" {
onCompletion(true)
} else {
onCompletion(false)
}
}
}
isCurrentDocumentPDF() {
isPDF in
if isPDF {
pdfDownloadButton.isHidden = false
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With