起因:升级XCode15后,打包完发现在iOS17中,前端无法通过navigator.userAgent获取设定的参数。
分析:WebKit在2023年6月的一次提交中,已经提到了会删除通过NSUserDefaults获取UserAgent的代码,原因客户端应使用 API 来设置UserAgent。
We should remove the code in UserAgentIOS.mm that reads an override UA from the NSUserDefault [com.apple.WebFoundation UserAgent]. It is incompatible with the modern need to compose the UA from various bits of information these days (e.g. desktop vs. mobile). Clients should use the API to set the application name or UA instead. I have stumbled upon one client (com.fark.hey), and there are likely others, so it should be a linked-on-or-after change.
在UserAgentIOS.mm源码中,也确实新增了一个函数判断
if (!linkedOnOrAfterSDKWithBehavior(SDKAlignedBehavior::DoesNotOverrideUAFromNSUserDefault)) {
if (auto override = dynamic_cf_cast<CFStringRef>(adoptCF(CFPreferencesCopyAppValue(CFSTR("UserAgent"), CFSTR("com.apple.WebFoundation"))))) {
static BOOL hasLoggedDeprecationWarning = NO;
if (!hasLoggedDeprecationWarning) {
NSLog(@"Reading an override UA from the NSUserDefault [com.apple.WebFoundation UserAgent]. This is incompatible with the modern need to compose the UA and clients should use the API to set the application name or UA instead.");
hasLoggedDeprecationWarning = YES;
}
return override.get();
}
}
这里说一下最终效果,有兴趣的同学也可以继续深挖一下:
1、使用XCode15以下的版本构建应用,iOS17或以下版本均可以通过NSUserDefaults设置UserAgent并且获取到设置的值
2、使用XCode15及以上版本构建应用,iOS17以下版本还是可以通过NSUserDefaults设置并获取,但iOS17及以上版本不支持
总结:
1、可以通过WKWebViewConfiguration直接设置
OC:
WKWebViewConfiguration *config = [[WKWebViewConfiguration alloc] init];
config.applicationNameForUserAgent = [NSString stringWithFormat:@"%@%@", configuration.applicationNameForUserAgent, @"自定义内容"];
WKWebView *webView = [[WKWebView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT)
configuration:config];
Swift:
let config = WKWebViewConfiguration()
config.applicationNameForUserAgent = "\(config.applicationNameForUserAgent ?? "") 自定义内容"
webView = WKWebView(frame: view.bounds, configuration: config)
2、通过customUserAgent设置
网友评论