iOS userAgent

User-Agent(用户代理)字符串是Web浏览器用于声明自身型号版本并随HTTP请求发送给Web服务器的字符串,在Web服务器上可以获取到该字符串。

在公司产品中,在userAgent中增加了NetType字段,用于标识客户端当前的网络环境。

  • NetType/WIFI
  • NetType/3G

web服务器端根据NetType类型加载不同分辨率的商品图片。我们只有两种,WIFI下高清图,非WIFI低分辨率图。

一、如何获取UserAgent

UIWebView方式:
  • UIWebView *webView = [[UIWebView alloc] initWithFrame:CGRectZero];
  • NSString *userAgent = [webView stringByEvaluatingJavaScriptFromString:@"navigator.userAgent"];
  • DLog(@"userAgent :%@", userAgent);
WKWebView方式:

// 注意这个方法是异步的

  • WKWebView *wkWebView = [[WKWebView alloc] initWithFrame:CGRectZero];
  • [wkWebView evaluateJavaScript:@"navigator.userAgent" completionHandler:^(id result, NSError *error) { DLog(@"userAgent :%@", result); }];

二、如何修改UserAgent

方案一,修改全局UserAgent值(这里是在原有基础上拼接自定义的字符串)
  • - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
  • UIWebView *webView = [[UIWebView alloc] initWithFrame:CGRectZero];
  • NSString *userAgent = [webView stringByEvaluatingJavaScriptFromString:@"navigator.userAgent"];
  • NSString *newUserAgent = [userAgent stringByAppendingString:@" native_iOS"];
  • //自定义需要拼接的字符串 NSDictionary *dictionary = [NSDictionary dictionaryWithObjectsAndKeys:newUserAgent, @"UserAgent", nil];
  • [[NSUserDefaults standardUserDefaults] registerDefaults:dictionary]; }
方案二,自定义UserAgent值
  • WKWebView *wkWebView = [[WKWebView alloc] initWithFrame:self.view.bounds];
  • [self.view addSubview: wkWebView];
  • NSString *customUserAgent = @"native_iOS";
  • [[NSUserDefaults standardUserDefaults] registerDefaults:@{@"UserAgent":customUserAgent}];
  • [[NSUserDefaults standardUserDefaults] synchronize];
  • [self.wkWebView setCustomUserAgent:customUserAgent];
  • NSURL *url = [NSURL URLWithString:self.strUrl];
  • NSURLRequest *request = [NSURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:10.f];
  • [self.wkWebView loadRequest:request];
方案三
  • self.wkWebView = [[WKWebView alloc] initWithFrame:self.view.bounds];
  • __weak typeof(self) weakSelf = self;
  • [self.wkWebView evaluateJavaScript:@"navigator.userAgent" completionHandler:^(id result, NSError *error) {
  • __strong typeof(weakSelf) strongSelf = weakSelf;
  • NSString *userAgent = result;
  • NSString *newUserAgent = [userAgent stringByAppendingString:@" native_iOS"];
  • NSDictionary *dictionary = [NSDictionary dictionaryWithObjectsAndKeys:newUserAgent, @"UserAgent", nil];
  • [[NSUserDefaults standardUserDefaults] registerDefaults:dictionary];
  • [[NSUserDefaults standardUserDefaults] synchronize];
  • [strongSelf.wkWebView setCustomUserAgent:customUserAgent];
  • strongSelf.wkWebView = [[WKWebView alloc] initWithFrame:strongSelf.view.bounds];
  • }];
  • [self.wkWebView loadRequest:request];

 

posted @ 2018-08-01 11:10  一二三开花  阅读(847)  评论(0编辑  收藏  举报