Alexander Alexander - 1 month ago 10x
iOS Question

Add request header to ALL outgoing requests within a WKWebView

TL;DR: I've got an iOS (Swift) project with a WKWebView. I want to add a request header to ALL outgoing requests (html, images, scripts, stylesheets, etc.) within this WKWebView. I can't find out how to do this. HALP!


I've got a Swift iOS application which uses a WKWebView to render it's html views. These views are hosted on our servers, which is divided into a production environment and an staging environment. I've set up the staging environment using Akamai so that all incoming request musts pass along a request header in order for the request to get accepted.

The issue:

Currently, I've created a subclass of WKWebView which overrides the loadRequest method, which looks something like this:

override func loadRequest(request: NSURLRequest) -> WKNavigation? {
guard let mutableRequest = request.mutableCopy() as? NSMutableURLRequest else {
return super.loadRequest(request)

if let url = request.URL, host = {
if (host == "") {
mutableRequest.setValue("secret-value", forHTTPHeaderField: "secret-header")

return super.loadRequest(mutableRequest)

This catches the initial html request, which works as expected. However, since this page in it's turn loads both images, stylesheets and scripts from the same server, these does not go through the loadRequest method and gets denied because their request lack this required request header.

I've tried to Google which methods to use to solve this, but have come out blank. Any help to solve this is appreciated. Thank you in advance!


It has got to work with WKWebView on iOS 8+.


It is impossible with current API - there is no point where you can handle all requests that made by WKWebView. You can use UIWebView + custom url protocol (WKWebView doesn't support it) and add your header to all requests for certain server as an alternative.