2

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.

Community
  • 1
  • 1
Mehul Mistri
  • 15,037
  • 14
  • 70
  • 94
  • Have you tried directly modifying the request passed to you (instead of launching a new one)? – Chris Trahey Aug 08 '12 at 06:11
  • It worth noting that you are relying on scope to distinguish two distinct variables both called `request` (a block has access to it's parent scope). In other words, you have a variable called `request` in scope, and then create another version of it. It's not exactly wrong, but can be confusing and degrades readability/maintainability – Chris Trahey Aug 08 '12 at 06:14
  • @ctrahey Please see my updated question.. Can plz tell me what is wrong with this and give me any suggestion for this – Mehul Mistri Aug 08 '12 at 06:17

2 Answers2

4

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.

Janak Nirmal
  • 22,706
  • 18
  • 63
  • 99
1

I am not sure what exactly is your situation. But for me, simply just setting baseURL parameter in -loadHTMLString:baseURL:; will automatically add HTTP header Referer as baseURL to all outgoing request under the HTML page.

partyspy
  • 31
  • 4