0

I know I can use the below code to change the default agent:

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

but I want to request a different User-Agent for different requests. Examples: request 'www.google.com', use agent=‘google Agent’, request 'www.github.com', use agent='github Agent'.

I have tried the below way to set the 'User_Agent' in each request, but it doesn't seem to work.

- (void)viewDidLoad {
    NSString *urlAddress = @"http://www.amazon.com";

    //Create a URL object.
    NSURL *url = [NSURL URLWithString:urlAddress];

    //URL Requst Object
    NSMutableURLRequest *requestObj = [NSMutableURLRequest requestWithURL:url];
    [requestObj setValue:@"Foobar/1.0" forHTTPHeaderField:@"User_Agent"];

    // But the value is not "Foobar/1.0"
    NSString* secretAgent = [webView stringByEvaluatingJavaScriptFromString:@"navigator.userAgent"]; 
    NSLog(@"agent - %@", secretAgent); 

    //Load the request in the UIWebView.
    [webView loadRequest:requestObj];
}

One more question:

It seems a change to the default agent only work change in 'AppDelegate' or 'initialize'. Am I right? Because I try to change in 'viewDidLoad' but it doesn't seem to work.

rmaddy
  • 314,917
  • 42
  • 532
  • 579
林晖杰
  • 61
  • 10

2 Answers2

0
  • I observed that if you load any url in webView with a user-agent set to it. After some time you load the different url & different user agent but used the same allocated WebView instane.The web view will load the new url but can not set new user-agent. It just set old one that you have set before loading first time.
  • You can not change untill you initiate new instanse of UIWebview(or we can say that user agent can be set once per session). So I coame to result that user-agent can be set only once.
  • What I did for this problem is, I allocated new instance when I want set new user-agent.
Rohit Pradhan
  • 3,867
  • 1
  • 21
  • 29
  • You can probably use the delegate `shouldStartLoadWithRequest` to manually request each page instead. Just return `NO` and load it by hand after changing the header. – EricS Oct 13 '16 at 04:57
0

You don't need to set it using JavaScript.

You have misspelled User-Agent. Use this minimal code taken from here

NSString* userAgent = @"My Cool User Agent";
NSURL* url = [NSURL URLWithString:@"http://whatsmyuseragent.com/"];
NSMutableURLRequest* request = [[NSMutableURLRequest alloc] initWithURL:url];
[request setValue:userAgent forHTTPHeaderField:@"User-Agent"];
Community
  • 1
  • 1
Anuj Rajput
  • 836
  • 9
  • 30
  • i use your way to try, seems the User-Agent also can not to change. – 林晖杰 Oct 13 '16 at 06:18
  • After request finished, i use `NSLog(@"User Agent - %@", [self.protocolWebView stringByEvaluatingJavaScriptFromString:@"navigator.userAgent"]);` to check the webView, it also print out the default agent – 林晖杰 Oct 13 '16 at 06:21