29

I've got a problem working with one remote server. My app makes a request to a server using [NSData initWithContentsOfURL:] method and as a response I get website's url which I open in UIWebView.

The problem is that those requests have different User-Agent and server can't serve me correct because it expects that I send all requests with the same User-Agent. I know how to change User-Agent (e.g Change User Agent in UIWebView (iPhone SDK)) but what I really want it is somehow to get UIWebView's User-Agent and set it to [NSData initWithContentsOfURL:] to avoid problems with server side

Community
  • 1
  • 1
Dmytro
  • 2,522
  • 5
  • 27
  • 36

2 Answers2

69

I just ran into a similar issue and needed to make the user agent sent by an NSURLConnection match the one sent by a UIWebView. My solution was to create a UIWebView and then just use javascript to pull out the user agent.

UIWebView* webView = [[UIWebView alloc] initWithFrame:CGRectZero];
NSString* secretAgent = [webView stringByEvaluatingJavaScriptFromString:@"navigator.userAgent"];
nate
  • 813
  • 8
  • 5
  • Note that you must use this code on the main thread - which makes sense, given it's use of UIKit, but is highly inconvenient. – emma ray Nov 20 '14 at 15:41
  • This seems to not work when I run on device. It works fine in the Simulator – RPM May 10 '17 at 21:27
7

As @nate mentioned above, you can invoke Javascript in a webview:

UIWebView* webView = [[UIWebView alloc] initWithFrame:CGRectZero];
NSString* secretAgent = [webView stringByEvaluatingJavaScriptFromString:@"navigator.userAgent"];

But invoking new Javascript is a bit hacky and creating a zero-size webView is gratuitous, since you already have a webView you're dealing with.

Alternatively you can simply use native methods on your given webView:

NSString* ua = [webView.request valueForHTTPHeaderField:@"User-Agent"];
NSLog(@"User-Agent = %@", ua);
Community
  • 1
  • 1
JohnK
  • 6,865
  • 8
  • 49
  • 75
  • I would second @JohnK's alternative method to use native API instead of injecting js for better readability/semantics. – Chrispy Jun 29 '15 at 20:20
  • Both these methods unfortunately require the request/response to already be processed so the programmer needs to consider this when reading the value asynchronously. – Henry Heleine Mar 29 '16 at 17:04