我创建了一个简单的iOS应用程序,使用WKWebView打开URL。在网站上有一个链接指向PDF文档。当我在浏览器上打开该网站时,我可以点击链接并打开PDF文档。但是在我的应用程序中,当我点击链接时没有反应。
我该怎么解决?我需要在我的info.plist中添加什么吗?
SWIFT 3.* & 4.* *
首先,您需要将PDF文件下载到您的应用程序中。下载后,您需要获取该文件路径,然后在WKWebView
中使用以下方式使用该文件路径。
let fileURL = URL(fileURLWithPath: filePathURLData as! String)
//print(fileURL)
webView.loadFileURL(fileURL, allowingReadAccessTo: fileURL)
在这里,filePathURLData
是您已经下载到应用程序中的实际文件路径,您需要将其转换为URL
,然后将该文件加载到WKWebView
中。
谢谢
希望这可以帮助您。
这将在WKWebView
中显示任何文件(doc、docx、xlsx、pdf、Google文档、Pages和任何文本文件)
webView.uiDelegate = self
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;
}
}
我遇到了同样的问题,并发现 PDF 文件使用的是不安全的 http
。因此,应用程序拒绝打开它。
请尝试检查 https
链接并查看是否有效。
另外,使用 WKWebView
,您无需在打开之前下载 PDF 文件。只需直接加载 URL 即可,例如:
webView.load(URLRequest(url: URL(string: "https-pdf-link")!))
Objective C:
NSURL *fileUrl = [[NSURL alloc] initWithString:filePathURLData];
[webView loadFileURL:fileUrl allowingReadAccessToURL:fileUrl];
打开保存在文档目录中的PDF文件的另一种方法:
NSData *data = [NSData dataWithContentsOfFile:fileURL];
[webView loadData:data MIMEType:@"application/pdf" characterEncodingName:@"" baseURL:[NSURL URLWithString:fileURL]];
WKWebView
中显示什么链接,您都必须先下载它。 - Abhishek Mitra