Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Send custom headers with UIWebView loadRequest

I want to be able to send some extra headers with my UIWebView loadRequest method.

I have tried:

NSMutableURLRequest *req = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http://www.reliply.org/tools/requestheaders.php"]];
[req addValue:@"hello" forHTTPHeaderField:@"aHeader"];

[self.theWebView loadRequest:req];

I have also tried subclassing the UIWebView and intercepting the - (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType method.

In that method I had a block of code which looked like this:

NSMutableURLRequest *newRequest = [request mutableCopy];
for(NSString *key in [customHeaders allKeys]) {
    [newRequest setValue:[customHeaders valueForKey:key] forHTTPHeaderField:key];
}
[self loadRequest:newRequest];

But for some unknown reason it was causing the web view to not load anything (blank frame) and the error message NSURLErrorCancelled (-999) comes up (all known fixes don't fix it for me).

So I am at a loss as to what to do. How can I send a custom header along with a UIWebView request?

Many thanks!

like image 348
Thomas Clayson Avatar asked Oct 11 '12 16:10

Thomas Clayson


2 Answers

I found that this was the way to add headers to my UIWebView request - override this delegate method:

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

With this code:

BOOL headerIsPresent = [[request allHTTPHeaderFields] objectForKey:@"my custom header"]!=nil;

if(headerIsPresent) return YES;

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
    dispatch_async(dispatch_get_main_queue(), ^{
        NSURL *url = [request URL];
        NSMutableURLRequest* request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];

        // set the new headers
        for(NSString *key in [self.customHeaders allKeys]){
            [request addValue:[self.customHeaders objectForKey:key] forHTTPHeaderField:key];
        }

        // reload the request
        [self loadRequest:request];
    });
});
return NO;
like image 89
Thomas Clayson Avatar answered Oct 31 '22 08:10

Thomas Clayson


The answer by Thomas will not work for (most of the) webpages with multiple iFrames. The solution will load an iFrame request over the full UIWebView. E.g. in case it calls loadRequest for a Google advt. (which is in some small iFrame) the advt. is loaded all over the UIWebView & nothing else.

like image 25
msk Avatar answered Oct 31 '22 08:10

msk