这个问题以前也有人问过。但我的要求不一样。我有这样的工作流程
使用WKWebView()
,情况就不是这样了。
如有任何帮助,将不胜感激。
我的CodeBase到现在为止
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下载
发布于 2020-01-14 06:15:30
尝试从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)
...
}
https://stackoverflow.com/questions/59597179
复制