Support file downloading in WKWebView

Hello,

I have a simple app to show web application in WKWebView.

The main problem is when the user clicks the link to download file then the WKWebView is trying to display this file instead of download.

Is it possible to implement somehow the possibility to download the file when users clics the link to this file?

The link to file doesn't include a file name in URL (for example: http://domain/rest/getFile).


I have implemented method "decidePolicyForNavigationAction" but then I don't know how to download this file by URL.


BR,

Paweł

Replies

You would be able to get the URL from the URLRequest provided to the delegate method, and then use the NSData(contentsOf:) initializer to download the content at that URL, right?

You would be able to get the URL from the URLRequest provided to the delegate method

Right.

and then use the

NSData(contentsOf:)
initializer to download the content at that URL, right?

Please don’t use these synchronous convenience routines for general-purpose networking. You should, instead, do the download using

URLSession
. Specifically, you can create a download session task that will download directly to the file system, and optionally continue the download even if you app is suspended in the background.

Share and Enjoy

Quinn “The Eskimo!”
Apple Developer Relations, Developer Technical Support, Core OS/Hardware

let myEmail = "eskimo" + "1" + "@apple.com"

Hello,

Thanks for your answers.


Now I'm able to get the right URL to file from request in delegate method and then create a URLSession to download file but I've found another problem.

The URLSession is not able to download file because of missing session. I'm using WKWebView and it seems that the cookies are not stored in cookie storage so the URLSession get a login page instead of file.

Is there any way to get cookies from WKWebView to use by URLSession? I was trying to get cookies from response header but without success.


BR,

Pawel

The URLSession is not able to download file because of missing session.

Right. This is a common problem, so common that WKWebView in the current beta OSes (iOS 11 beta and so on) includes a new API to get at the required cookies. You can learn more about this in WWDC 2017 Session 220 Customized Loading in WKWebView.

On current OS releases your options depend on whether the cookie is flagged as

HttpOnly
or not:
  • If it’s not HTTP only, you can get the cookie by executing JavaScript within the web view to access the

    document.cookies
    DOM property.
  • If it is HTTP only, things get much more ‘fun’.

Share and Enjoy

Quinn “The Eskimo!”
Apple Developer Relations, Developer Technical Support, Core OS/Hardware

let myEmail = "eskimo" + "1" + "@apple.com"