WKWebView 修改UA方案 兼容iOS8
2018-09-21 本文已影响192人
嫌疑人zx
我们有一个需求,需要在在原本UA的基础上添加一个值 XXX.app.ios_版本号
代码需要写在AppDelegate中
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions;
注意:否者,不能及时被更改!
1.导入头文件:
#import <WebKit/WebKit.h>
2.获取当前的版本号:
#define Version [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleVersion"] //build 版本号
3.系统控制:
#define iOS9 ([[UIDevice currentDevice].systemVersion doubleValue] >= 9.0)
示例代码:
#pragma mark - 全局修改UA
-(void)modificationUA{
WKWebView *wk = [[WKWebView alloc] init];
NSString *currentUserAgent = [NSString stringWithFormat:@"XXX.app.ios_%@",Version];
if (iOS9) {
[wk evaluateJavaScript:@"navigator.userAgent" completionHandler:^(id result, NSError *error) {
NSString *oldAgent = result;
if (error) {
oldAgent = [[[UIWebView alloc] init] stringByEvaluatingJavaScriptFromString:@"navigator.userAgent"];
}
if (![oldAgent hasPrefix:currentUserAgent]) {
NSString *customUserAgent = [NSString stringWithFormat:@"%@ %@", currentUserAgent, oldAgent];
[[NSUserDefaults standardUserDefaults] registerDefaults:@{@"UserAgent":customUserAgent, @"User-Agent":customUserAgent}];
}
}];
}else{//适配iOS8,下面的方法不能少
NSString *oldAgent = [[[UIWebView alloc] init] stringByEvaluatingJavaScriptFromString:@"navigator.userAgent"];
if (![oldAgent hasPrefix:currentUserAgent]) {
NSString *customUserAgent = [NSString stringWithFormat:@"%@ %@", currentUserAgent, oldAgent];
NSDictionary *dictionnary = [[NSDictionary alloc] initWithObjectsAndKeys:customUserAgent, @"UserAgent", nil];
[[NSUserDefaults standardUserDefaults] registerDefaults:dictionnary];
[wk setValue:customUserAgent forKey:@"applicationNameForUserAgent"];
}
}
}