Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to read MIME type of a page with WKWebView?

My app navigates to a mobile web page with a WKWebView. What I'm looking for is how to check whether or not the web page is downloadable (e.g. a .csv or .pdf). Right now, I'm doing something hacky to read the URL, but I know there must be a more elegant way.

I'm using WKNavigationDelegate - can anyone provide some insight on how to tell whether a page provides downloadable content or not? Or how I can read a type of "text/csv"?

Please let me know if I can clarify at all.

like image 887
ArielSD Avatar asked Jan 29 '23 12:01

ArielSD


1 Answers

You should be able to inspect the response and get the MIME type before the page loads, using the webView(_:decidePolicyFor:decisionHandler:) method of your WKNavigationDelegate.

Set an object as the navigationDelegate for your WKWebView, and give it a method like this:

func webView(_ webView: WKWebView, 
        decidePolicyFor navigationResponse: WKNavigationResponse, 
        decisionHandler: @escaping (WKNavigationResponsePolicy) -> Void) {

    if let mimeType = navigationResponse.response.mimeType {
        // do some thing with the MIME type
    } else {
        // response has no MIME type, do some special handling
    }
    decisionHandler(.allow)
}
like image 156
Aaron Frary Avatar answered Feb 04 '23 03:02

Aaron Frary