获取 UIWebview 的 Useragent,以及附加自定义字段到 Useragent

来源:互联网 发布:网上怎么开淘宝 编辑:程序博客网 时间:2024/06/06 15:45

获取 UIWebview 的useragent

关于获取 UIWebview 的useragent。我对网上的一种做法实在画面太美不忍看。他们使用UIWebview 去加载一个请求,通过返回来数据(附有 UserAgent 的参数)来获取Useragent,这种做法需要设置webview 代理、发请求、要解析数据、要处理用完的对象。

实际上只需要两行代码就能搞定

[objc] view plaincopyprint?
  1. UIWebView* webView = [[UIWebView alloc] initWithFrame:CGRectZero];  
  2. NSString* secretAgent = [webView stringByEvaluatingJavaScriptFromString:@"navigator.userAgent"];  

[objc] view plaincopyprint?
  1. <span style="font-size: 14px;">secretAgent</span>  
这样我们就已经拿到了 useragent。

secretAgent值为: Mozilla/5.0 (iPhone; CPU iPhone OS 7_1 like Mac OS X) AppleWebKit/537.51.2 (KHTML, like Gecko) Mobile/11D167


附加自定义字段到 Useragent中

[objc] view plaincopyprint?
  1. NSString *newUagent = [NSString stringWithFormat:@"%@ appname/3.5.2",secretAgent];  
  2. NSDictionary *dictionary = [[NSDictionary alloc]  
  3.                                 initWithObjectsAndKeys:newUagent, @"UserAgent", nil nil];  
  4. [[NSUserDefaults standardUserDefaults] registerDefaults:dictionary];  

这里我们附加的是appname,以及对应的版本号。

newUagent值为: Mozilla/5.0 (iPhone; CPU iPhone OS 7_1 like Mac OS X) AppleWebKit/537.51.2 (KHTML, like Gecko) Mobile/11D167 appname/3.5.2

0 0
原创粉丝点击