How to open a Link to a PDF with wkwebview

前端 未结 3 619
有刺的猬
有刺的猬 2020-12-10 07:15

I created a simple iOS app, which opens a URL with WKWebView. On the website, there is a link to a PDF Document. When I open the site on my browser, I can click onto the Lin

相关标签:
3条回答
  • 2020-12-10 07:43

    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")!)
    
    0 讨论(0)
  • 2020-12-10 07:49

    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;
        }
    }
    
    0 讨论(0)
  • 2020-12-10 07:52

    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)

    0 讨论(0)
提交回复
热议问题