2

Just migrated an app over to WKWebView and was wondering if there is any possible way to 'preload' multiple URLs, but only display one at a time?

I have a list of 5 URLs. I already know that I will be shown at some point in time, and I want to speed up the experience by pre-loading these for use in a single WKWebView.

casillas
  • 16,351
  • 19
  • 115
  • 215
JimmyJammed
  • 9,598
  • 19
  • 79
  • 146

4 Answers4

4

I ended up just using NSURLCache and preloading all URLs using NSURLRequest and NSURLConnection. Then whenever I load a url into WKWebView it uses the cached requests per my cache policy.

JimmyJammed
  • 9,598
  • 19
  • 79
  • 146
  • 1
    Can you go into a bit more detail as to how you achieved this using the 'load' method? The URLRequests don't seem to cache (maybe it depends on the response headers?). – sdasdadas Nov 01 '16 at 11:05
2

A relatively straight-forward way to do this is to create five NSData objects (asynchronoulsly), each initialized using the known urls. When you need to display one of them, you can convert the NSData to a string, and then call WKWebView's loadHTMLString function to change the displayed page.

0

You can also preload five different WKWebView instances and swap them in/out when you need a specific URL. This depends on your UI and interaction of course.

Stefan Arentz
  • 34,311
  • 8
  • 67
  • 88
0

Use NSURLCache

Here is the code

Swift

// Create URLRequest
    var request: URLRequest? = nil
    if let url = URL(string: "YOUR_URL") {
        request = URLRequest(url: url)
    }
    
    // Check the cache.
    var cachedResponse: CachedURLResponse? = nil
    if let request = request {
        cachedResponse = URLCache.shared.cachedResponse(for: request)
    }
    print(cachedResponse != nil ? "Cached response found!" : "No cached response found.")
   // Load the cache
    do {
        if let request = request {
            try NSURLConnection.sendSynchronousRequest(request, returning: nil)
        }
    } catch {
    }

Obj-C

NSURLRequest *request = [[NSURLRequest alloc] initWithURL:[NSURL URLWithString:@"YOUR_URL"]];

    // Check the cache.
    NSCachedURLResponse *cachedResponse = [[NSURLCache sharedURLCache] cachedResponseForRequest:request];
    NSLog(cachedResponse ? @"Cached response found!" : @"No cached response found.");
    //Load cache
    [NSURLConnection sendSynchronousRequest:request returningResponse:NULL error:NULL];
Wonixer A
  • 116
  • 12