Change User Agent in UIWebView

前端 未结 14 1836
孤城傲影
孤城傲影 2020-11-22 17:03

I have a business need to be able to customize the UserAgent for an embedded UIWebView. (For instance, I\'d like the server to respond differently if, say, a user is using

相关标签:
14条回答
  • 2020-11-22 18:07

    Actually adding any header field to the NSURLRequest argument in shouldStartLoadWithRequest seems to work, because the request responds to setValue:ForHTTPHeaderField - but it doesn't actually work - the request is sent out without the header.

    So I used this workaround in shouldStartLoadWithRequest which just copies the given request to a new mutable request, and re-loads it. This does in fact modify the header which is sent out.

    if ( [request valueForHTTPHeaderField:@"MyUserAgent"] == nil )
    {
        NSMutableURLRequest *modRequest = [request mutableCopyWithZone:NULL];
        [modRequest setValue:@"myagent" forHTTPHeaderField:@"MyUserAgent"];
        [webViewArgument loadRequest:modRequest];
        return NO;
    }
    

    Unfortunately, this still doesn't allow overriding the user-agent http header, which is apparently overwritten by Apple. I guess for overriding it you would have to manage a NSURLConnection by yourself.

    0 讨论(0)
  • 2020-11-22 18:08

    Taking everything this is how it was solved for me:

    - (void)viewDidLoad {
        NSURL *url = [NSURL URLWithString: @"http://www.amazon.com"];
        NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
        [request setValue:@"Foobar/1.0" forHTTPHeaderField:@"User-Agent"];
        [webView loadRequest:request];
    }
    

    Thanks Everyone.

    0 讨论(0)
提交回复
热议问题