Mobile Development 14 min read

Comprehensive Guide to Using WKWebView in iOS: Creation, Delegates, UserAgent, Cookies, and JS Interaction

This article provides a detailed tutorial on WKWebView for iOS, covering its creation, configuration, delegate methods, custom UserAgent registration, cookie management, native‑H5 communication, JavaScript bridges, and NSURLRequest caching strategies, offering practical code examples and best‑practice tips.

Sohu Tech Products
Sohu Tech Products
Sohu Tech Products
Comprehensive Guide to Using WKWebView in iOS: Creation, Delegates, UserAgent, Cookies, and JS Interaction

Since iOS 8.0, WKWebView from the WebKit framework replaces UIWebView for loading web content, offering lower memory usage, richer HTML5 support, and finer‑grained request control. Apple also announced that UIWebView will be deprecated after December 2020, making WKWebView essential for modern iOS apps.

Creating WKWebView

- (WKWebView *)webView {
    if (_webView) {
        return _webView;
    }
    WKUserContentController *userContentController = [[WKUserContentController alloc] init];
    [userContentController addScriptMessageHandler:[[WKWeakScriptMessageDelegate alloc] initWithDelegate:self] name:@"jsCallOC"];
    WKWebViewConfiguration *webViewConfig = [[WKWebViewConfiguration alloc] init];
    webViewConfig.userContentController = userContentController;
    webViewConfig.processPool = [[self cookieManager] sharedProcessPool];
    webViewConfig.allowsInlineMediaPlayback = true;
    _webView = [[WKWebView alloc] initWithFrame:CGRectMake(0, CGRectGetHeight(self.iTopBar.frame), self.view.bounds.size.width, (self.view.bounds.size.height - CGRectGetHeight(self.iTopBar.frame))) configuration:webViewConfig];
    _webView.backgroundColor = [UIColor whiteColor];
    _webView.scrollView.backgroundColor = [UIColor blackColor];
    _webView.opaque = NO;
    _webView.scrollView.showsHorizontalScrollIndicator = NO;
    _webView.scrollView.showsVerticalScrollIndicator = NO;
    _webView.autoresizingMask = UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleWidth;
    _webView.scrollView.bounces = !self.disableBounces;
    _webView.UIDelegate = self;
    _webView.navigationDelegate = self;
    return _webView;
}

The configuration includes WKUserContentController for JavaScript‑to‑native messaging, a shared WKProcessPool for cookie sharing, and allowsInlineMediaPlayback to enable in‑page video playback.

Key Delegate Methods

// WKNavigationDelegate examples
- (void)webView:(WKWebView *)webView didStartProvisionalNavigation:(WKNavigation *)navigation;
- (void)webView:(WKWebView *)webView didCommitNavigation:(WKNavigation *)navigation;
- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation;
- (void)webView:(WKWebView *)webView didFailNavigation:(WKNavigation *)navigation withError:(NSError *)error;
- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler;

// WKUIDelegate examples
- (void)webView:(WKWebView *)webView runJavaScriptAlertPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(void))completionHandler;
- (void)webView:(WKWebView *)webView runJavaScriptTextInputPanelWithPrompt:(NSString *)prompt defaultText:(nullable NSString *)defaultText initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(NSString * _Nullable result))completionHandler;
- (void)webView:(WKWebView *)webView runJavaScriptConfirmPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(BOOL result))completionHandler;
- (WKWebView *)webView:(WKWebView *)webView createWebViewWithConfiguration:(WKWebViewConfiguration *)configuration forNavigationAction:(WKNavigationAction *)navigationAction windowFeatures:(WKWindowFeatures *)windowFeatures;

The decidePolicyForNavigationAction method works like shouldStartLoadWithRequest in UIWebView, allowing interception of link clicks. When targetFrame.isMainFrame is NO , developers can load the request in the current web view to handle new‑page links.

Custom UserAgent Registration

// iOS 9+ custom UA
[webView evaluateJavaScript:@"navigator.userAgent" completionHandler:^(id obj, NSError *error) {
    if ([obj isKindOfClass:[NSString class]]) {
        NSString *userAgent = (NSString *)obj;
        if (![userAgent containsString:@"customUA"]) {
            userAgent = [userAgent stringByAppendingString:@"customUA"];
        }
        [[NSUserDefaults standardUserDefaults] registerDefaults:@{ @"UserAgent": userAgent }];
        [[NSUserDefaults standardUserDefaults] setObject:userAgent forKey:uaKey];
        self.webView.customUserAgent = userAgent;
    }
}];

// iOS 8 fallback
[self.webView setValue:userAgent forKey:@"applicationNameForUserAgent"];

For iOS 8, setting the value via KVC avoids crashes.

Cookie Management

WKWebView does not automatically attach cookies from NSHTTPCookieStorage . The article recommends using a shared WKProcessPool and a dedicated cookie‑loading web view to inject cookies via JavaScript.

- (void)setCookieWithUrl:(NSURL *)url {
    NSString *host = [url host];
    if (!self.webviewCookie.length) { [self requestWKWebviewCookie]; return; }
    if ([self.cookieURLs containsObject:host]) return;
    [self.cookieURLs addObject:host];
    WKUserScript *wkcookieScript = [[WKUserScript alloc] initWithSource:self.webviewCookie injectionTime:WKUserScriptInjectionTimeAtDocumentStart forMainFrameOnly:NO];
    [self.cookieWebview.configuration.userContentController addUserScript:wkcookieScript];
    NSString *baseWebUrl = [NSString stringWithFormat:@"%@://%@", url.scheme, url.host];
    [self.cookieWebview loadHTMLString:@"" baseURL:[NSURL URLWithString:baseWebUrl]];
}

- (WKWebView *)cookieWebview {
    if (!_cookieWebview) {
        WKUserContentController *userContentController = WKUserContentController.new;
        WKWebViewConfiguration *webViewConfig = WKWebViewConfiguration.new;
        webViewConfig.userContentController = userContentController;
        webViewConfig.processPool = [self sharedProcessPool];
        _cookieWebview = [[WKWebView alloc] initWithFrame:CGRectZero configuration:webViewConfig];
        _cookieWebview.UIDelegate = self;
        _cookieWebview.navigationDelegate = self;
    }
    return _cookieWebview;
}

Using a singleton WKProcessPool allows multiple WKWebViews to share cookies.

Native‑H5 Interaction

Two common approaches are shown:

Intercepting custom URL schemes in decidePolicyForNavigationAction to extract parameters.

Registering a WKScriptMessageHandler (e.g., jsCallOC ) to receive JSON messages from JavaScript.

// JS → OC via message handler
- (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message {
    NSLog(@"[WebView] : H5 call name: %@, body: %@", message.name, message.body);
    if ([message.name isEqualToString:@"jsCallOC"] && [message.body isKindOfClass:[NSString class]]) {
        NSDictionary *result = [message.body JSONDictionary];
        NSString *value = [result stringOrEmptyStringForKey:@"value"];
        // handle value
    }
}

// OC → JS
NSString *OCCallJs = [NSString stringWithFormat:@"OCCallJs('%@')", value];
[self.webView evaluateJavaScript:OCCallJs completionHandler:nil];

JavaScript can invoke the native side with window.webkit.messageHandlers.jsCallOC.postMessage(JSON.stringify(data)); .

NSURLRequest Cache Policies

The article lists the NSURLRequestCachePolicy enum values and explains how HTTP headers such as Cache-Control , Expires , Last-Modified , If-Modified-Since , Etag , and If-None-Match influence caching behavior.

In summary, the guide covers the essential aspects of WKWebView usage, from initialization and delegate handling to advanced topics like custom UserAgent, cookie sharing, and JavaScript bridges, providing ready‑to‑use Objective‑C snippets for iOS developers.

mobile developmentiOSWebKitWKWebViewObjective-CCookie ManagementJavaScript Bridge
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.