iOS 13 WKWebView 不再显示 pdf 文件

iOS 13 WKWebView not showing pdf file anymore

我正在使用 WKWebView 显示来自远程 url 的 pdf 文件。它在 iOS 12 中工作正常,但在 iOS 13 中它只是显示空白屏幕。 我用图像 url 访问了同一个域,效果很好,但它只对 pdf 个文件有一些问题。

let myURL = URL(string:"somefileurl.pdf") // If I hit this url in safari, It will download a pdf file.
let myRequest = URLRequest(url: myURL!)
webViewPdf.load(myRequest)  

对于 PDF 在我的案例中试试这个 100% 工作

func openFile(url:URL){
self.displayDocument(filePath: url, type: "pdf")
}



 extension Your ViewControler Name :UIDocumentInteractionControllerDelegate{

            public func documentInteractionControllerViewControllerForPreview(_ controller: UIDocumentInteractionController) -> UIViewController {
                UINavigationBar.appearance().tintColor = UIColor.blue
                return self
            }

            public func documentInteractionControllerDidEndPreview(_ controller: UIDocumentInteractionController) {
                UINavigationBar.appearance().tintColor = UIColor.clear
                self.documentInteractionController = nil
            }
            func documentInteractionControllerDidDismissOptionsMenu(_ controller: UIDocumentInteractionController) {
                UINavigationBar.appearance().tintColor = UIColor.clear
                self.navigationController?.dismiss(animated: false, completion: nil)
            }

            func displayDocument(filePath:URL,type:String){
                SVProgressHUD.dismiss()

                self.documentInteractionController = UIDocumentInteractionController(url:filePath )
                // Preview PDF
                self.documentInteractionController.delegate = self
                self.documentInteractionController.presentPreview(animated: true)
            }
        }

我发现响应'内容类型"application/octet-stream"而不是"application/pdf"

所以我将 WKWebView 加载为:

if let myURL = URL(string:"somefileurl.pdf") {
    if let data = try? Data(contentsOf: myURL) {
       webViewPdf.load(data, mimeType: "application/pdf", characterEncodingName: "", baseURL: myURL)
    }
}

UIWebView也有同样的问题。固定如下(objective-c):

[self.webView loadData:data MIMEType:@"application/pdf" textEncodingName:@"" baseURL:[NSURL URLWithString:@"FilePathOrUrlString"];

只需实现 WKNavigationDelegate 中可用的 decidePolicyFor 方法,如下所示,

func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {
   decisionHandler(.allow)
}

并在您的网络视图中设置委托,如下所示,

yourWebView.navigationDelegate = self