It feels hacky, but I solved it by doing a WKWebView execution of some javascript that fetches the contents via ajax and returns it to completionHandler in swift.
Background
WKWebView supports the evaluateJavaScript call, which passes the javascript result to completionHandler :
func evaluateJavaScript(_ javaScriptString: String, completionHandler completionHandler: ((AnyObject?, NSError?) -> Void)?)
Since there is jQuery on the server side, I used this to send ajax , as shown below. But of course this can be done using javascript .
(function(url) { var result = ''; $.ajax({ type: 'GET', url: url, success: function(r) {result = r}, failure: function() {result = null}, async: false }); return result })(url)
url can be passed in javascript with fast string interpolation .
Extend WKWebView
To easily use this, I have expanded the WKWebView class.
// Views/WKWebView.swift import WebKit extension WKWebView { func readUrlContent(url: NSURL, completionHandler: (result: String) -> Void) { self.evaluateJavaScript("(function() { var result = ''; $.ajax({type: 'GET', url: '\(url)', success: function(r) {result = r}, failure: function() {result = null}, async: false }); return result })()", completionHandler: { (response, error) -> Void in let result = response as! String completionHandler(result: result) }) } }
Using
From an example question, this can be called as follows:
let url = navigationAction.request.URL! if url.pathExtension == "ics" { decisionHandler(WKNavigationActionPolicy.Cancel) webView.readUrlContent(url) { (result: String) in print(result)