8

My iOS UIWebView page is based on Cordova open source framework, and I want to add some customize http headers in its webview URL request, my solution is to add them in the following UIWebView delegate method.

Debug shows that headers are added successfully, but in fact the request doesn't bring them out. Using Wireshark to capture network packets and found only standard headers are available, no my customize ones.

My testing is based on simulator (iOS 7.1), anyone who has experience on this topic please share and discuss together, thanks in advance.

- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
{
    // Add customize http headers in UIWebView request
    if([request isKindOfClass:[NSMutableURLRequest class]]) {        

        NSMutableURLRequest * mRequest = (NSMutableURLRequest *)request;
        [mRequest setValue:@"1.1" forHTTPHeaderField:@"appVersion"];
        [mRequest setValue:@"iPhone 4S" forHTTPHeaderField:@"deviceModel"];
    }

    return [super webView:webView shouldStartLoadWithRequest:request navigationType:navigationType];
}
jianhua
  • 1,011
  • 1
  • 12
  • 28

5 Answers5

22

I know its late but may help others for SWIFT 3.0

let weburl = NSURL(string: "http://www.mywebsite.com")
    let request = NSMutableURLRequest(URL: weburl!)
    request.setValue("HEADER_VALUE", forHTTPHeaderField:"HEADER_NAME")
    myWebView.loadRequest(request)
Umair Khalid
  • 2,259
  • 1
  • 21
  • 28
  • 1
    It works! I had to enable App Transport Security Settings -> Allow Arbitrary Loads in Web Content = YES override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. let weburl = URL(string: "https://myserverxx.com") let request:NSMutableURLRequest = NSMutableURLRequest(url:weburl!) request.setValue("myvalue", forHTTPHeaderField:"MyKEY") webview.delegate = self webview.loadRequest(request as URLRequest); } – ashish Feb 01 '17 at 18:20
  • How do you test it? https://www.whatismybrowser.com/detect/what-http-headers-is-my-browser-sending looks doesn't recognize it – Federico Picci Feb 09 '17 at 12:07
  • @UmairKhalid ok.... I was testing on that website because i don't have a service yet. – Federico Picci Feb 10 '17 at 09:20
5

Sometimes Cookies are not set even after you assign all http headers. it is better to create mutable request and copy your nsurlrequest and add your custom header to it so that all information from original request is retained in mutable one.

- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest*)request navigationType:(UIWebViewNavigationType)navigationType
{

  if(check if key not present){
  NSMutableURLRequest *re = [[NSMutableURLRequest alloc] init];//alloc init      not required
  re = (NSMutableURLRequest *) request.mutableCopy;
  [re setValue:@"Your Custom Value" forHTTPHeaderField:@"Yout Custom     Header"];
      [webView loadRequest:re] ;
  return NO;

  }
return YES;

}
Satyam Raikar
  • 465
  • 6
  • 20
3

You have two options either create a NSMutableUrlRequest at the start and load that with webView loadReqest or take over the complete URL loading of your app with NSURLProtocol.

The most easiest way is the first choice as its only one extra lines of code:

[webView loadRequest:mRequest];

The second choice uses NSURLProtocol to take over URL loading of your app. this involves registering your own solution using creating a concrete class. the main method to override is canonicalRequestForRequest.

I suggest you take a look at these two tutorials NSNipster and raywenderlich for guides.

Shams Ahmed
  • 4,498
  • 4
  • 21
  • 27
  • Thanks Shams, finally I choose #1 by hacking Cordova code. – jianhua Aug 29 '14 at 10:25
  • @jianhua I'm currently working on the same thing, can you update your question with your final solution, by chance? – ephbaum Dec 14 '14 at 03:54
  • NSURL protocol is the actual way to handle this. But it is tricky to handle when ajax is involved. Ajax calls needs to be async if any present in website code. – Satyam Raikar Jun 30 '15 at 03:56
  • The headers wont load when it is kind of redirecting, some web requests load under navigationType other and without headers, if we force them to do with headers, they don't redirect. – Amber K Dec 24 '18 at 10:48
3

Swift 5.2 Solution

By making URLRequest & setValue

@IBOutlet var wkWebView: WKWebView!
let url = URL(string: "https://YouAreBest.com")
var request = URLRequest(url: url!)
request.setValue("1", forHTTPHeaderField:"userid")
wkWebView.load(request)
Jack
  • 13,571
  • 6
  • 76
  • 98
0

a pure Swift 4 compliance answer should be something like the following:

if let anURL = URL(string: aString) {
    var aRequest = URLRequest(url: anURL, cachePolicy: .reloadIgnoringCacheData, timeoutInterval: 5.0)
    if let tmpToken = Network.shared.getAuthenticationToken() {
        aRequest.setValue(tmpToken, forHTTPHeaderField: "Authorization")
    }
    self.loadRequest(aRequest)
}

where cachePolicy, timeoutInterval are to be set following your needs, as well as the if let statement in order to get an hypothetical token to be inserted in the request.

The relevant part here is the way you set additional parameters on the URLRequest. No needs to use a Mutable statement anymore. var is the you go on the URLRequest.

valvoline
  • 7,737
  • 3
  • 47
  • 52