Send custom headers with UIWebView loadRequest Send custom headers with UIWebView loadRequest ios ios

Send custom headers with UIWebView loadRequest


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;


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.


I find another way, Can use NSURLProtocol .

-(BOOL)webView:(IMYVKWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType{    NSMutableDictionary* mapObject = [NSMutableDictionary dictionary];    mapObject[@"headers"] = request.allHTTPHeaderFields;    mapObject[@"navigationType"] = @(navigationType);    [webViewRequestMap setObject:mapObject forKey:request.URL.absoluteString];    return YES;}

webViewRequestMap is Static NSMutableDictionary*

in Your Custom NSURLProtocol code:

    @interface IMYCustomURLProtocol : NSURLProtocol@end@implementation IMYCustomURLProtocol +(void)load{     [NSURLProtocol registerClass:self];}+ (BOOL)canInitWithRequest:(NSURLRequest *)request{    NSString* urlString = request.URL.absoluteString;    NSDictionary* dictionary = webViewReuqestMap[urlString];    if (dictionary)    {        [webViewRequestMap removeObjectForKey:urlString];        if ([request isKindOfClass:[NSMutableURLRequest class]]) {           [(id)request setValue:@"HAHA" forHTTPHeaderField:@"MeiYou Co.,Ltd"];        }    }    return NO;}@end