Last Updated: August 01, 2022
·
26.99K
· artchang

Preloading UIWebView or WKWebView in Swift

Description

The key to preloading a WebView (either UIWebView or WKWebView), is to call viewDidLoad before the view appears. The trick is that in viewDidLoad you have the WKWebView or UIWebView ready to execute a loadRequest ahead of time. The first controller the app launches should perform the preload kick off.

Steps:

  1. In your viewDidLoad override for the WebView controller, set the url and load the request (you can async this request to a background thread, but know that the request still happens in the main thread asynchronously, it shouldn't block).
  2. In the first controller (such as a MainTabBar or some intro screen you have), you will call the viewDidLoad of the WebView. Let's assume you do this in a UITabBarController. The controller YourWebViewController you see is a reference to your webview controller.

UITabBarController

override func viewDidLoad() {
    super.viewDidLoad()
    // getWebViewController() is a helper that gets the right controller. You can implement this however you want, but you should
    //    easily be able to get this from the viewControllers on a UITabBarController or any other ViewController
    if let webViewController = getWebViewController() {
        dispatch_async(dispatch_get_main_queue(), { () -> Void in
            // this will asynchronously call the viewDidLoad, but will not layout everything yet and will not block the main thread
            webViewController.view.setNeedsLayout()
            // do not call webViewController.view.layoutIfNeeded() here, because that will block the main thread in a RELEASE mode, which sucks big time
        )}
      }
    }

YourWebViewController

override func viewDidLoad() {
  super.viewDidLoad()
  let url = "https://priime.com/some/great/endpoint"
  let request = NSURLRequest(URL: url)
  // This webView is the UIWebView or WKWebView
  webView.loadRequest(request)
}

Related protips:

Some simple Swift Extensions (Strip HTML, RGB Color, Color invert, Dismiss modal segue)

2 Responses
Add your response

Thanks Arthur,

I'm trying to get this to work but I seem to get stuck at getting the WKWebView to my CustomTabBarController from my ViewController.

Could you give me an example of that? I'm just looking to load one specific WKWebView named webView.

over 1 year ago ·

Mind being more specific with your comment in the code. Im not following. Show us the code for getWebViewController

//getWebViewController() is a helper that gets the right controller. You can implement this however you want, but you should
// easily be able to get this from the viewControllers on a UITabBarController or any other ViewController

over 1 year ago ·