我正在使用“ webview”组件访问网站。在站点的不确定部分中,我们具有.pdf和.ppt格式的文件。 用户单击这些文件时可以下载吗?今天,该应用程序仅打开.pdf和.ppt,但我想下载它。
我的代码在pt_BR中。
class PortalAcademicoViewController: UIViewController {
@IBOutlet weak var webView: UIWebView!
override func viewDidLoad() {
super.viewDidLoad()
carregaSite()
}
func carregaSite(){
/*
let url = URL(string: "")
var urlRequest = URLRequest(url: url!)
urlRequest.cachePolicy = .returnCacheDataElseLoad
webView.loadRequest(urlRequest) */
//carregar o arquivo html
let htmlFile = Bundle.main.path(forResource: "portalacademico", ofType: "html")
let html = try? String(contentsOfFile: htmlFile!, encoding: String.Encoding.utf8)
HTTPCookieStorage.shared.cookieAcceptPolicy = .always
self.webView.frame = self.view.bounds
webView.loadHTMLString(html!, baseURL: Bundle.main.resourceURL)
//voltar e avançar entres as paginas do webview
let swipeLeftRecognizer = UISwipeGestureRecognizer(target: self, action: #selector(handleSwipe(recognizer:)))
let swipeRightRecognizer = UISwipeGestureRecognizer(target: self, action: #selector(handleSwipe(recognizer:)))
swipeLeftRecognizer.direction = .left
swipeRightRecognizer.direction = .right
webView.addGestureRecognizer(swipeLeftRecognizer)
webView.addGestureRecognizer(swipeRightRecognizer)
//fim
}
//trabalhando com avançar e voltar webview
@objc private func handleSwipe(recognizer: UISwipeGestureRecognizer) {
if (recognizer.direction == .left) {
if webView.canGoForward {
webView.goForward()
}
}
if (recognizer.direction == .right) {
if webView.canGoBack {
webView.goBack()
}
}
}
//FIM
}
答案 0 :(得分:1)
I think you should perform download task with Javascript. Check your requests in func webView(_ webView: WKWebView, decidePolicyFor navigationAction ...) and if there download request found call the javascript method.
Here is someone already done pdf download with wkwebview.
答案 1 :(得分:1)
您可以将UIWebViewDelegate设置为WebView,并在webViewShouldStartLoadWithRequest中检查PDF和PPT文件。每次用户单击链接时都会调用webViewShouldStartLoadWithRequest。
func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
if reqeust for a PPT or PDF file {
downloadFile()
return false
}
return true
}
https://developer.apple.com/documentation/uikit/uiwebviewdelegate/1617945-webview?language=objc
侧面说明:您当前正在使用不推荐使用的UIWebView。您应该考虑改用WKWebView。
答案 2 :(得分:0)
使用 WKWebView 下载.pdf和.ppt或任何特定文件,请在此处查看我的解决方案