How to add HTTP headers in request globally for iOS in swift

sandip picture sandip · Mar 11, 2015 · Viewed 34.7k times · Source
func webView(webView: WKWebView!, decidePolicyForNavigationAction navigationAction: WKNavigationAction!, decisionHandler: ((WKNavigationActionPolicy) -> Void)!) {
     var request = NSMutableURLRequest(URL: navigationAction.request.URL)
     request.setValue("value", forHTTPHeaderField: "key")
     decisionHandler(.Allow)
}

In the above code I want to add a header to the request. I have tried to do navigationAction.request.setValue("IOS", forKey: "DEVICE_APP") but it doesn't work.

please help me in any way.

Answer

Stefan Arentz picture Stefan Arentz · Mar 12, 2015

AFAIK sadly you cannot do this with WKWebView.

It most certainly does not work in webView:decidePolicyForNavigationAction:decisionHandler: because the navigationAction.request is read-only and a non-mutable NSURLRequest instance that you cannot change.

If I understand correctly, WKWebView runs sandboxed in a separate content and network process and, at least on iOS, there is no way to intercept or change it's network requests.

You can do this if you step back to UIWebView.