Download files in a Web View | Part2

Krishna kushwaha
2 min readJan 6, 2023

--

I’ll show you how to detect a mime type you may be interested into (PDF, Excel etc.) and instead of letting the WKWebView open it save the file with a URLSession and then offer the user the ability to move the file with a share sheet.

As usual you can find all the code in on GitHub

It is a simple View Controller that instantiates the class WKWebViewDownloadHelper. The class is the navigationDelegate of the WKWebView and is responsible for detecting the correct mimeType, download the file and call its delegate with the path of the file.

When browsing the web in our WKWebView we may want to download some kind of files. A web view is perfectly capable of displaying a PDF document, but although it supports a basic view of an Excel file you may want to open it with Numbers or MS Excel.

Our class is the navigationDelegate for the WKWebView and we have two methods called each time the page wants to redirect to a new URL.
The first one is decidePolicyFor navigationAction, and the second is decidePolicyFor navigationResponse. The latter is called when we received the first response from the server, we can still tell the web view to avoid opening the URL and we need this method so we can parse the response to read the HTTP headers.

Add this in your view controller

var helper:WKWebviewDownloadHelper!

Add also this in your view controller under viewdidload method

let mimeTypes = [MimeType(type: "ms-excel", fileExtension: "xls"),
MimeType(type: "pdf", fileExtension: "pdf")]
helper = WKWebviewDownloadHelper(webView: webView, mimeTypes:mimeTypes, delegate: self)

Add extension n your view controller

extension ViewController: WKWebViewDownloadHelperDelegate {
func fileDownloadedAtURL(url: URL) {
DispatchQueue.main.async {
let activityVC = UIActivityViewController(activityItems: [url], applicationActivities: nil)
activityVC.popoverPresentationController?.sourceView = self.view
activityVC.popoverPresentationController?.sourceRect = self.view.frame
activityVC.popoverPresentationController?.barButtonItem = self.navigationItem.rightBarButtonItem
self.present(activityVC, animated: true, completion: nil)
}
}
}

Thanks for reading………………………….!

--

--