//本文用于在userAgent后添加标识字段(dbios/版本号)
前言
- H5页面获得的UserAgent都是默认的UserAgent,而不是修改后的UserAgent,原因在于webView会将userAgent替换为默认。
- 直接在加载webView处更改无效,故而我们在AppDelegate里面的
- (BOOL)application:(UIApplication )application didFinishLaunchingWithOptions:(NSDictionary )launchOptions
方法里修改默认的UserAgent。该方法能保证userAgent成功被修改。
正文
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
// Override point for customization after application launch.
//修改userAgent,在后面添加字段
//判断版本号
NSDictionary *infoDictionary = [[NSBundle mainBundle] infoDictionary];
// NSString *appCurVersionNum = [infoDictionary objectForKey:@"CFBundleVersion"];
// NSLog(@"当前应用版本号码:%@",appCurVersionNum);
NSString *appCurVersion = [infoDictionary objectForKey:@"CFBundleShortVersionString"];
NSLog(@"当前应用软件版本:%@",appCurVersion);
UIWebView * tempWebView = [[UIWebView alloc] initWithFrame:CGRectZero];
NSString * oldAgent = [tempWebView stringByEvaluatingJavaScriptFromString:@"navigator.userAgent"];
NSString * newAgent = oldAgent;
//此处在userAgent后添加加* dbios/版本号*
if (![oldAgent hasSuffix:@" dbios"]) {
newAgent = [oldAgent stringByAppendingString:[NSString stringWithFormat:@" dbios/%@",appCurVersion]];
}
NSLog(@"new agent :%@", newAgent);
NSDictionary * dictionnary = [[NSDictionary alloc] initWithObjectsAndKeys:newAgent, @"UserAgent", nil];
[[NSUserDefaults standardUserDefaults] registerDefaults:dictionnary];
[[NSUserDefaults standardUserDefaults] synchronize];
return YES;
}