Mobile Development 22 min read

Comprehensive Guide to WKWebView: Migration, Performance, Delegates, Caching, and Cookie Management

This article explains why UIWebView was deprecated, how WKWebView improves performance and memory usage, details its multi‑process architecture, outlines page loading flow, delegate methods, container design, caching strategies, cookie handling across processes, and solutions for white‑screen crashes in iOS apps.

Sohu Tech Products
Sohu Tech Products
Sohu Tech Products
Comprehensive Guide to WKWebView: Migration, Performance, Delegates, Caching, and Cookie Management

Previously UIWebView was used for loading web pages, but it suffered from high memory consumption and poor performance and was officially removed by Apple in 2020; therefore this article focuses on WKWebView, which has been supported since iOS 8 and is now the standard for most apps.

WKWebView offers significantly better performance than UIWebView, achieving up to 60 FPS refresh rates and lower memory usage, because it runs network, UI rendering, and JavaScript execution in separate processes, isolating crashes from the main app process.

The page loading process includes DNS resolution, TCP/TLS handshake, HTML retrieval, parsing of HTML/XML/CSS/JS, DOM construction, and final rendering, with asynchronous loading of resources and possible JavaScript‑induced DOM modifications.

Delegate methods have changed: WKUIDelegate allows custom handling of alerts, prompts, and other UI interactions before rendering, while WKNavigationDelegate provides callbacks such as decidePolicyForNavigationAction, didStartProvisionalNavigation, didFailProvisionalNavigation, and didFinishNavigation to manage navigation decisions, loading progress, and error handling.

For container design, a WKWebViewController wrapper is recommended to keep the web view presentation logic separate from business logic, exposing navigation bar, title, and progress bar configuration via WKWebViewConfiguration.

A reuse pool can be implemented to share WKWebView instances across the app, reducing the heavy initialization cost by maintaining visiblePool and reusablePool collections.

WKProcessPool enables sharing of cookies, cache, and other data between multiple WKWebView instances, allowing a single process to serve multiple web views.

User‑Agent strings can be customized on iOS 9+ using the customUserAgent property, or via JavaScript injection on earlier versions.

Caching strategies follow standard NSURLRequest policies (e.g., NSURLRequestUseProtocolCachePolicy, ReloadIgnoringLocalCacheData) and HTTP headers like Cache‑Control, Last‑Modified, and ETag to control freshness and validation.

Cookie management is complex because WKWebView and the app store cookies in separate memory spaces; the article recommends synchronizing cookies using NSHTTPCookieStorage for network requests and injecting JavaScript via WKUserContentController for web‑view cookies, with fallback to WKHTTPCookieStore on iOS 11+.

Example code for adding a cookie to WKWebView:

- (void)addCookieWithDict:(NSDictionary *)dict forHost:(NSString *)host {
    [dict enumerateKeysAndObjectsUsingBlock:^(NSString * _Nonnull key, NSString * _Nonnull value, BOOL * _Nonnull stop) {
        NSMutableDictionary *properties = [NSMutableDictionary dictionary];
        [properties setObject:key forKey:NSHTTPCookieName];
        [properties setObject:value forKey:NSHTTPCookieValue];
        [properties setObject:host forKey:NSHTTPCookieDomain];
        [properties setObject:@"/" forKey:NSHTTPCookiePath];
        [properties setValue:[NSDate dateWithTimeIntervalSinceNow:60*60*72] forKey:NSHTTPCookieExpires];
        NSHTTPCookie *cookie = [NSHTTPCookie cookieWithProperties:properties];
        [[NSHTTPCookieStorage sharedHTTPCookieStorage] setCookie:cookie];
    }];
}

To remove all WKWebView cookies:

- (void)removeWKWebviewCookie {
    self.webviewCookie = nil;
    [self.cookieWebview.configuration.userContentController removeAllUserScripts];
    NSMutableArray
*cookies = [NSMutableArray array];
    [[NSHTTPCookieStorage sharedHTTPCookieStorage].cookies enumerateObjectsUsingBlock:^(NSHTTPCookie * _Nonnull cookie, NSUInteger idx, BOOL * _Nonnull stop) {
        if ([self.cookieData.allKeys containsObject:cookie.name]) {
            [cookies addObject:cookie];
        }
    }];
    [cookies enumerateObjectsUsingBlock:^(NSHTTPCookie * _Nonnull cookie, NSUInteger idx, BOOL * _Nonnull stop) {
        [[NSHTTPCookieStorage sharedHTTPCookieStorage] deleteCookie:cookie];
    }];
}

White‑screen issues caused by WKWebView process crashes can be detected using the webViewWebContentProcessDidTerminate: callback (iOS 9+) or by checking if webView.title is empty before displaying the view.

performanceiOSWebViewcachingWKWebViewcookie
Sohu Tech Products
Written by

Sohu Tech Products

A knowledge-sharing platform for Sohu's technology products. As a leading Chinese internet brand with media, video, search, and gaming services and over 700 million users, Sohu continuously drives tech innovation and practice. We’ll share practical insights and tech news here.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.