0xSina
0xSina

Reputation: 21553

UIWebView iOS5 changing user-agent

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;
}

Upvotes: 37

Views: 28961

Answers (3)

Zaid Pathan
Zaid Pathan

Reputation: 16820

In Swift use this to set UserAgent,

func setUserAgent(){

    var userAgent = NSDictionary(objectsAndKeys:  "YourUserAgentName","UserAgent")

    NSUserDefaults.standardUserDefaults().registerDefaults(userAgent as [NSObject : AnyObject])

}

Use this to test,

println(WebView.stringByEvaluatingJavaScriptFromString("navigator.userAgent"));

Upvotes: 1

Martin Wickman
Martin Wickman

Reputation: 19905

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+

Upvotes: 89

funberry
funberry

Reputation: 1

When you send message [aWebView loadData:MIMEType:textEncodingName:baseURL:]

then aWebView shouldStartLoadWithRequest: will be called again, and then again - that is why you get an infinite recursion

You should restrict calling of your dispatch_async() block, for example by using some conventional URL:

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


    if ([[[request URL] absoluteString] isEqualToString:@"http://yourdomain.com/?local=true"]) {
        return YES;
    }


    ...

    dispatch_async(...
            [aWebView loadData:data 
                      MIMEType:[response MIMEType] 
              textEncodingName:[response textEncodingName] 
                       baseURL:[NSURL URLWithString:@"http://yourdomain.com/?local=true"]];

    );
    return NO;
}

Upvotes: 0

Related Questions