因为我们app原生和H5交互都是依靠设置WKWebView的userAgent实现交互,线上反馈一台手机点击按钮没反应,因为点击按钮是给到原生端处理,通过日志发现设置userAgent不成功导致。
解决方法如下:
网上资料如下,都是创建一个假的webView,最后设置真是webView的userAgent即可。
这么做确实是首个页面设置成功了,但是进到app里面页面又存在设置不上的问题,因为我们的设置userAgent的都是在每个webView的didStartProvisionalNavigation代理方法设置的。
最后是在AppDelegate文件全局设置userAgent解决了。
代码如下:
#pragma mark - 设置全局userAgent
//修改userAgent
- (void)addToWebViewUserAgent {
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
WKWebView *webView = [WKWebView new];
[webView evaluateJavaScript:@"navigator.userAgent" completionHandler:^(id _Nullable oldAgent, NSError * _Nullable error) {
if (![oldAgent isKindOfClass:[NSString class]]) {
// 为了避免没有获取到oldAgent,所以设置一个默认的userAgent
// Mozilla/5.0 (iPhone; CPU iPhone OS 12_2 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/15E148
oldAgent = [NSString stringWithFormat:@"Mozilla/5.0 (%@; CPU iPhone OS %@ like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/15E148", [[UIDevice currentDevice] model], [[[UIDevice currentDevice] systemVersion] stringByReplacingOccurrencesOfString:@"." withString:@"_"]];
}
NSString *userAgent = oldAgent;
//修改UserAgent
NSString *newUserAgent = [userAgent stringByAppendingString:@"C2Mobile/{1.0.0}"];
if (![newUserAgent containsString: @" SmartChasing"]) {
//修改UserAgent
newUserAgent = [newUserAgent stringByAppendingString:@" SmartChasing"];
}
NSString *barHeight = [NSString stringWithFormat:@";statusBarHeight:%f",kStatusBarHeight];
newUserAgent = [newUserAgent stringByAppendingString:barHeight];
[webView setCustomUserAgent:newUserAgent];
NSDictionary *userAgentDic = @{@"UserAgent": newUserAgent};
[[NSUserDefaults standardUserDefaults] registerDefaults:userAgentDic];
}];
});
}