//本文用于在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;
}