How to open a Link to a PDF with wkwebview
SWIFT 3.* & 4.* *
First you have to download that pdf file into your app, after downloading you have to get that file path, then that file path should be use like following way in WKWebView
.
let fileURL = URL(fileURLWithPath: filePathURLData as! String)
//print(fileURL)
webView.loadFileURL(fileURL, allowingReadAccessTo: fileURL)
Here filePathURLData
is your actual file path which you have downloaded into your app, you have to convert this into URL
, then you need to load that file into WKWebView
Thanks
Hope this will help you.
This will show any file in the WKWebView
(doc, docx, xlsx, pdf, google doc, pages & Any textfile)
Objective C:
NSURL *fileUrl = [[NSURL alloc] initWithString:filePathURLData];
[webView loadFileURL:fileUrl allowingReadAccessToURL:fileUrl];
Another way to open PDF saved in document directory:
NSData *data = [NSData dataWithContentsOfFile:fileURL];
[webView loadData:data MIMEType:@"application/pdf" characterEncodingName:@"" baseURL:[NSURL URLWithString:fileURL]];
I have same issue, and found out the pdf file is using unsecured http
. Therefore the app refuse to open it.
Try to check with https
link and see if it works.
Also with WKWebView
, you don't need to download the pdf file before open it. Just load the url directly, i.e
webView.load(URLRequest(url: URL(string: "https-pdf-link")!))
Likely, you are using target="_blank" in your anchor tag. That opens up a new window to display the link. WKWebView is blocking your attempt to open a new window (at least by default).
The code below still does not create a new window, but instead opens the PDF, etc link in the current WKWebView. The other option seems to be to create a new WKWebView and return it, so the ios and open the link in that, but I don't want extra Views being created by every click on a website inside the WKWebView.
In your ViewController.viewDidLoad
webView.uiDelegate = self
Then add the extension for the delegate
extension ViewController: WKUIDelegate {
/**
* Force all popup windows to remain in the current WKWebView.
* By default, WKWebView is blocking new windows from being created
* ex <a href="link" target="_blank">text</a>.
* This code catches those popup windows and displays them in the current WKWebView.
*/
func webView(_ webView: WKWebView, createWebViewWith configuration: WKWebViewConfiguration, for navigationAction: WKNavigationAction, windowFeatures: WKWindowFeatures) -> WKWebView? {
// open in current view
webView.load(navigationAction.request)
// don't return a new view to build a popup into (the default behavior).
return nil;
}
}