Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WKWebView and NSURLCache to serve local content

My app loads a very big webapp inside a UIWebView.

I have written a NSURLCache extension "LocalCache".

This LocalCache extension intercepts my webapp loading, and serves all requested files from a local app bundle that is encrypted. This logic is implemented in NSURLCache's cachedResponseForRequest method. So the app is served 100% locally:

class LocalCache:NSURLCache {
    override func cachedResponseForRequest( request: NSURLRequest) -> NSCachedURLResponse? {
        if (request points to my domain) {
            get file from bundle
            decrypt it
            return local copy
        } else {
            return super.cachedResponseForRequest(request)
        }
    }
}

NSURLCache.setSharedURLCache(LocalCache());

I'd like to port this functionality to WKWebkit. I wonder if there's a way to implement something similar, because unfortunately, as you probably know, WKWebView does not use the Cocoa stack with NSProtocol, NSUrl, NSUrlCache .... rendering my current approach useless.

So, can something similar be accomplished with WkWebView?

Note: The fact that UiWebView "thinks" that my app comes from a remote server is key for the application: If I just load the application locally, ie. file://, there is a lot of stuff that doesn't work, for example, YouTube Videos, as youtube api complains that "file://" is not an approved origin. So the WkWebView solution I'm looking for has to be related to intercepting the cache rather than injecting local javascript.

like image 687
rupps Avatar asked Apr 11 '15 03:04

rupps


1 Answers

I was in a very similar position a few months ago (using NSURLProtocol / NSURLCache and wanting to migrate from UIWebView to WKWebView), and what I ended up doing was to use a local HTTP server to serve my files/requests (https://github.com/mattstevens/RoutingHTTPServer).

This also helped me deal with a different issue, which was related to loading HTML5 videos on the UIWebView, because some of the range requests were not being intercepted by the UIWebView / NSURLCache.

like image 195
André Morujão Avatar answered Nov 15 '22 12:11

André Morujão