Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

Background:
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 = 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'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.

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

like image 311
Alexander Avatar asked Oct 18 '22 01:10

Alexander


1 Answers

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.

like image 184
Roman Ermolov Avatar answered Oct 28 '22 22:10

Roman Ermolov