Search code examples
iphoneobjective-cipaduiwebviewhttp-referer

Specifying HTTP referer in UIWebView


How can we set HTTP referer in embedded UIWebView?

I had gone through this but still not got success.

1. In viewDidLoad, I wrote this code,

[objWebView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@"MY_URL"]]];

Here is my code :

- (BOOL) webView:(UIWebView*)webView shouldStartLoadWithRequest:(NSURLRequest*)request navigationType:(UIWebViewNavigationType) navigationType 
{
    NSDictionary *headers = [request allHTTPHeaderFields];
    BOOL hasReferer = [headers objectForKey:@"Referer"]!=nil;
    if (hasReferer) {
        // .. is this my referer?
        return YES;
    } else {
        // relaunch with a modified request
        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];
                [request setHTTPMethod:@"GET"];
                [request setValue:@"Referer link" forHTTPHeaderField:@"Referer"];
                [objWebView loadRequest:request];
            });
        });
        return NO;
    }
}

2. I had tried this also in viewDidLoad

NSMutableURLRequest* request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"MY_URL"]];
[request setValue:@"Referel URL" forHTTPHeaderField:@"Referer"];
[objWebView loadRequest:request];

But doesn't got success yet.

Please help me solve this problem or tell me is there any problem with this code or not?

Hope I presented question clearly.


Solution

  • You can set Default User-Agent using following code

    NSDictionary *dictionary = [[NSDictionary alloc] initWithObjectsAndKeys:@"Safari/528.16", @"UserAgent", nil];
    [[NSUserDefaults standardUserDefaults] registerDefaults:dictionary];
    

    It is well explained here.