Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 755
sandip Avatar asked Mar 11 '15 10:03

sandip


2 Answers

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.

like image 129
Stefan Arentz Avatar answered Sep 18 '22 15:09

Stefan Arentz


There are many different ways to do that, I found that the easiest solution was to subclass WKWebView and override the loadRequest method. Something like this:

class CustomWebView: WKWebView {     override func load(_ request: URLRequest) -> WKNavigation? {         guard let mutableRequest: NSMutableURLRequest = request as? NSMutableURLRequest else {             return super.load(request)         }         mutableRequest.setValue("custom value", forHTTPHeaderField: "custom field")         return super.load(mutableRequest as URLRequest)     } } 

Then simply use the CustomWebView class as if it was a WKWebView.

EDIT NOTE: This will only work on the first request as pointed out by @Stefan Arentz.

NOTE: Some fields cannot be overridden and will not be changed. I haven't done a thorough testing but I know that the User-Agent field cannot be overridden unless you do a specific hack (check here for an answer to that)

like image 41
Gabriel Cartier Avatar answered Sep 17 '22 15:09

Gabriel Cartier