一,前言--UA在项目中的应用
给项目的webview或项目中的接口请求加一个区分,用来区别是iOS端访问、android访问还是在浏览器访问的,这时需要添加User Agent (http请求 header中的一个参数)。
- 检查浏览器或设备的功能,并根据结果加载不同的CSS;
- 将自定义JavaScript与另一个设备相比较;
- 与桌面计算机相比,向手机发送完全不同的页面布局;
- 根据用户代理语言偏好自动发送文档的正确翻译;
- 根据用户的设备类型或其他因素向特定用户推送特惠优惠;
- 收集有关访问者的统计信息,以告知我们的网页设计和内容制作流程,或者仅仅衡量谁访问我们的网站,以及来自哪些引荐来源。
具体的UserAgent解释请参考这里
1. 用户代理 User Agent,是指浏览器,它的信息包括硬件平台、 系统软件、应用软件和用户个人偏好。
4. UserAgent简称UA,可以用作一个用户的真实访问,一般的Web统计流量也会针对UA信息去统计浏览器占比,移动占比等等。
1. 如何获取userAgent
* UIWebView :
NSString *oldUserAgent = [[[UIWebView alloc]init] stringByEvaluatingJavaScriptFromString:@"navigator.userAgent"];
[self evaluateJavaScript:@"navigator.userAgent" completionHandler:^(id _Nullable result, NSError * _Nullable error) { NSString *oldUserAgent = result;
}];
* UIWebView :
+ (void)registUserAgent {
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
UIWebView *webView = [[UIWebView alloc]initWithFrame:CGRectZero];
//修改UserAgent
NSString *oldUserAgent = [webView stringByEvaluatingJavaScriptFromString:@"navigator.userAgent"];
//自定义需要拼接的字
NSString *newUserAgent = [oldUserAgent stringByAppendingString:@"xxx"];
NSDictionary *dictionary = [NSDictionary dictionaryWithObjectsAndKeys:newUserAgent, nil];
[[NSUserDefaults standardUserDefaults] registerDefaults:dictionary];
[[NSUserDefaults standardUserDefaults] synchronize];
});
}
- (void)defaultUserAgentString:(NSMutableURLRequest *)request { [self evaluateJavaScript:@"navigator.userAgent" completionHandler:^(id _Nullable result, NSError * _Nullable error) { NSString *userAgent = result; if([userAgent rangeOfString:@"xxxx"].location ==NSNotFound){ userAgent = [NSString stringWithFormat:@"%@ x/1/%@",userAgent,[self appVersion]]; NSDictionary *dictionnary = [[NSDictionary alloc] initWithObjectsAndKeys:userAgent, @"UserAgent", nil]; [[NSUserDefaults standardUserDefaults] registerDefaults:dictionnary]; [[NSUserDefaults standardUserDefaults] synchronize]; }
if (@available(iOS 9.0, *)) { self.customUserAgent = userAgent; } else { [self setValue:userAgent forKey:@"User-Agent"]; } [self loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@"about:blank"]]];//重置空白界面 [self loadRequest:request]; }]; } //版本号 - (NSString *)appVersion { static NSString * __identifier = nil; if ( nil == __identifier ) { __identifier = [[[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleShortVersionString"] copy]; } return __identifier; }