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];
}
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.
a pure Swift 4 compliance answer should be something like the following:
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.
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:
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.