UIWebView iOS5 changing user-agent

0xSina picture 0xSina · Dec 13, 2011 · Viewed 28k times · Source

How can I change the user-agent of UIWebView in iOS 5?

What I have done so far: Using the delegate call back, intercept the NSURLRequest, create a new url request and set it's user-agent as whatever I want, then download the data and reload the UIWebView with "loadData:MIMEType:....".

Problem: This causes infinite recursion, where I load the data, which calls the delegate back, which intern calls the delegate....

Here's the delegate method:

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



    dispatch_async(kBgQueue, ^{
        NSURLResponse *response = nil;
        NSMutableURLRequest *newRequest = [NSMutableURLRequest requestWithURL:[request URL]];
        NSDictionary *headers = [NSDictionary dictionaryWithObject:
                                 @"custom_test_agent" forKey:@"User-Agent"];
        [newRequest setAllHTTPHeaderFields:headers];
        [self setCurrentReqest:newRequest];
        NSData *data = [NSURLConnection sendSynchronousRequest:newRequest 
                                             returningResponse:&response 
                                                         error:nil];
        dispatch_sync(dispatch_get_main_queue(), ^{
            [webView loadData:data 
                     MIMEType:[response MIMEType] 
             textEncodingName:[response textEncodingName] 
                      baseURL:[request URL]];
        });
    });

    return YES;
}

Answer

Martin Wickman picture Martin Wickman · Dec 29, 2011

Change the "UserAgent" default value by running this code once when your app starts:

NSDictionary *dictionary = [NSDictionary dictionaryWithObjectsAndKeys:@"Your user agent", @"UserAgent", nil];
[[NSUserDefaults standardUserDefaults] registerDefaults:dictionary];  

EDIT: I have used this with great success, but want to add additional details. To get a user agent, you can enable the "Developer" menu, set the user agent, and then connect to this site to get it printed out for you: WhatsMyAgent. Likewise you can connect using any kind of mobile device, and get it that way too. BTW this is still working just fine in iOS7+