Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
936 views
in Technique[技术] by (71.8m points)

swift - WkWebView does not load links to pdfs

The WKWebView is not loading links. I am linking users to a privacy policy page, and the page has a group of links. The links are all pdfs hosted by wix. On safari and Chrome it works, but not on WKWebView. When the page loads, and you click the links, I just get an error:

Unknown result for URL 0x28157d110 (https)

This is how I'm loading the web view...

webView.load(URLRequest(url: URL(string: "https://mywebsite.io/legal")!))

EDIT: This is different from other questions because I have no intention of downloading the pdf - I just want to display it the same way that Safari does.

EDIT: I just replaced WKWebView with UIWebView (deprecated) and the pdfs load. The issue is with WKWebView. The Pdfs are ssl-enabled https ->

let req = URLRequest(url: URL(string: "https://mywebsite.io/legal")!)
    legacyWebView.loadRequest(req)

EDIT: There is a page here How to open a Link to a PDF with wkwebview that suggests that you must know the link URL before opening the pdf, I don't think this is true though.

EDIT: I have 2 delegate methods implemented, including the one suggested below by @Kiril. Links to pdfs still do not open.

func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {
        decisionHandler(WKNavigationActionPolicy.allow)
    }
    func webView(_ webView: WKWebView, decidePolicyFor navigationResponse: WKNavigationResponse, decisionHandler: @escaping (WKNavigationResponsePolicy) -> Void) {
        decisionHandler(WKNavigationResponsePolicy.allow)
    }
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

There are a few things you can check:

  1. Verify that the <a href links doesn't contain target="_blank" attribute since WKWebView doesn't know how to open the link in a new tab. see https://stackoverflow.com/a/25853806/810466 for how to work around that.

  2. Check if the link is HTTPS or update the App Transport Security Settings with the Allow Arbitrary Loads option

  3. Make sure that you start the loading request only after adding the WKWebView to the view hierarchy in didMoveToParentViewController: since it may make javascript to fail if it tries to run outside the view hierarchy

  4. Implement the WKWebView NavigationDelegate methods and make sure you return WKNavigationActionPolicyAllow when deciding the policy for the request


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...