How to get UIWebView User-Agent

做~自己de王妃 提交于 2019-11-27 00:44:26

问题


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


回答1:


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"];



回答2:


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


来源:https://stackoverflow.com/questions/3297733/how-to-get-uiwebview-user-agent

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!