[英]Is it possible for a user to download PDF content displayed on WkWebView
[英]Is it possible to download a pdf from a authenticated session in wkwebview?
这个问题之前有人问过。 但我的要求不一样。 我有一个这样的工作流程
任何帮助将不胜感激
我的代码库到现在
import UIKit
import WebKit
class WebKitViewController: UIViewController {
@IBOutlet weak var webView: WKWebView!
var pdfUrl:URL!
override func viewDidLoad() {
super.viewDidLoad()
self.setViewContext()
}
func setViewContext() {
let url = URL(string: "https://www.example.com")!
webView.navigationDelegate = self
webView.load(URLRequest(url: url))
}
func downloadPDF(fromUrl url:String) {
guard let url = URL(string: url) else { return }
let urlSession = URLSession(configuration: .default, delegate: self, delegateQueue: OperationQueue())
let downloadTask = urlSession.downloadTask(with: url)
downloadTask.resume()
}
@IBAction func openPDFButtonPressed(_ sender: Any) {
let pdfViewController = PDFViewController()
pdfViewController.pdfURL = self.pdfUrl
present(pdfViewController, animated: false, completion: nil)
}}
extension WebKitViewController:WKNavigationDelegate{
func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {
if let host = navigationAction.request.url {
if host.absoluteString.contains("https://www.example.com/en/my-account/invoicePDF/"){
decisionHandler(.cancel)
print(host.absoluteString)
self.downloadPDF(fromUrl: host.absoluteString)
return
}
}
decisionHandler(.allow)
}
}
extension WebKitViewController: URLSessionDownloadDelegate {
func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didFinishDownloadingTo location: URL) {
print("downloadLocation:", location)
do {
let documentsURL = try
FileManager.default.url(for: .documentDirectory,
in: .userDomainMask,
appropriateFor: nil,
create: false)
let savedURL = documentsURL.appendingPathComponent("yourCustomName90.pdf")
self.pdfUrl = savedURL
try FileManager.default.moveItem(at: location, to: savedURL)
} catch {
print ("file error: \(error)")
}
}
}
注意 - macOS Safari 中的 pdf 下载
尝试从 webview 读取 cookie 并在打电话下载您的 pdf 之前保存它:
func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
self.webView.configuration.websiteDataStore.httpCookieStore.getAllCookies { cookies in
//save cookies
self.cookies = cookies
}
}
func downloadPDF(fromUrl url:String) {
guard let url = URL(string: url) else { return }
HTTPCookieStorage.shared.setCookies(cookies, for: url, mainDocumentURL:nil)
...
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.