Add request header to all outgoing requests in WKWebView

TL DR : I have an iOS project (Swift) with WKWebView. I want to add a request header to all outgoing requests (html, images, scripts, stylesheets, etc.) in this WKWebView. I can’t figure out how to do this.

Background:
I have a Swift iOS application that uses WKWebView to render html views. These views are hosted on our servers, which are divided into a production environment and an intermediate environment. I set up the staging environment using Akamai so that the entire incoming request must go along the request header in order for the request to be accepted.

Problem:
I have currently created a subclass of WKWebView that 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 = url.host {
        if (host == "staging.example.com") {
            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 includes downloading images, stylesheets and scripts from the same server, they do not go through the loadRequest method and are denied because their request does not have the required request header.

Requirements:
It must work with WKWebView on iOS 8+.

+4
source share
1 answer

API - , WKWebView. UIWebView + URL (WKWebView ) .

+3

Source: https://habr.com/ru/post/1654853/


All Articles