【问题标题】:Is it possible to download a pdf from a authenticated session in wkwebview?是否可以从 wkwebview 中经过身份验证的会话下载 pdf?
【发布时间】:2020-01-05 05:06:19
【问题描述】:

之前有人问过这个问题。但是我的要求不一样。我有这样的工作流程

  1. 用户使用 WKWebView() 登录应用
  2. 用户登录后有一个发票选项卡,他可以通过该选项卡单击按钮下载发票。
  3. 问题出现在这里。虽然桌面和安卓应用程序能够下载 pdf ,但在 iOS 中却无法下载。我尝试了许多解决方法,例如“decidePolicyFor”,一旦知道其 URL 就下载 pdf 等。
  4. 我认为是需要下载的普通 pdf 文件的问题通常在其 URL 的末尾有一个“.pdf”.. ex-“www.xyz.com/books.pdf”,但是我的就像这 - “www.xyz.com/library/id=10”
  5. 这也可能是因为服务器仅在经过身份验证后才授予对 pdf 的访问权限。如果我尝试直接使用 URL 下载,情况并非如此

任何帮助将不胜感激

我的代码库到现在

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 下载

【问题讨论】:

  • 据我所知,您的downloadTask 未经身份验证。实现URLSession 代表,您应该从他们那里获得更多信息
  • 登录后使用您自己的服务器获取响应,而不是作为会话密钥或任何知道用户已登录的信息,然后作为第二次安全检查,从您的 pdf url 附加会话密钥该用户可以访问该文件。登录时密钥是否一直更改并不重要(这是一个很好的做法),因此这是为您的任务实施的一种简单方法。 url 可能看起来像 host/useraccount/invoicePdf&securekey=....其他方法是在下载请求的标题中发送自定义密钥。
  • 您无法通过访问 URL 在 iPhone 上下载 PDF,但您可以使其显示在浏览器样式页面中
  • @Saamer 不正确,如果他到达 URL,他可以下载任何类型的文件。使用任何网络请求管理器都很简单,例如 Alamofire public static func download(_ url: URLConvertible, method: HTTPMethod = .get, parameters: Parameters? = nil, encoding: ParameterEncoding = URLEncoding.default, headers: HTTPHeaders? = nil,拦截器:RequestInterceptor? = nil,到目的地:...
  • 嗯,我认为我的措辞不正确。我的意思是说,它不像 Android 和 web,它不会通过点击链接自动下载文件

标签: ios objective-c swift


【解决方案1】:

在调用下载您的 pdf 之前尝试从 webview 读取 cookie 并保存它:

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)
    ...
}

【讨论】:

    猜你喜欢
    • 2012-06-02
    • 1970-01-01
    • 2014-06-12
    • 2021-06-10
    • 2019-10-30
    • 1970-01-01
    • 2013-06-24
    • 2012-09-05
    • 1970-01-01
    相关资源
    最近更新 更多