iOS问题纪录 - iOS 17通过NSUserDefaults设置UserAgent无效(续) ...

锦通  论坛元老 | 2024-6-21 14:07:32 | 显示全部楼层 | 阅读模式
打印 上一主题 下一主题

主题 1016|帖子 1016|积分 3048


媒介

在上篇文章中对该问题做了一些判断和推测,并给出了解决方案。不过,美中不足的是没有进一步验证推测,所以在这里进一步分析该问题作为上篇文章的增补。
开发情况



  • Xcode: 15.1
  • iOS: 17.2
问题描述

项目运行在iOS 17.2设备时,应用内网页无法成功获取设置后的UserAgent。
项目中设置UserAgent的关键源码:
  1. [self.webView evaluateJavaScript:@"navigator.userAgent" completionHandler:^(id result, NSError *error) {
  2.     NSString *userAgent = [NSString stringWithFormat:@"%@", result];
  3.     NSString *newUserAgent = [userAgent stringByAppendingString:@" App/1.0.0"];
  4.     [[NSUserDefaults standardUserDefaults] registerDefaults:@{@"UserAgent": newUserAgent}];
  5. }];
复制代码
问题分析

进一步分析的前提是有源码可以分析,好在WKWebView类属于WebKit.framework,这算是体系框架内里少有的开源框架。
1. 准备源码

找到GitHub上面的开源项目WebKit,通过以下下令克隆项目到本地:
  1. git clone https://github.com/WebKit/WebKit.git WebKit
复制代码
这项目有点大,最终占了约14GB的硬盘空间。因为后面大概需要搜索汗青提交纪录,所以我完备克隆了项目,如果你没有这个需求,可以按需浅克隆。
源码准备好了,现在可以直接用Xcode打开WebKit项目。那接下来该怎么定位导致该问题的关键源码呢?
2. 定位源码

一样平经常用的切入点有两个,各有各的优缺点:

  • 从WKWebView类开始分析源码。耗时比力长且容易找错方向,但只要不断分析,定位到关键源码不是问题,而且能让你对该项目有更多的熟悉
  • 用UserAgent作为关键词搜索相干的汗青提交纪录。运气好时能快速定位源码,运气不好时容易迷失方向
如果从WKWebView类开始分析源码,目前只知道早先可以通过NSUserDefaults设置UserAgent,所以要先确定导致该问题的改动大概是在什么时候提交的,然后再将源码切换到早于这个时候的提交,如许才有大概找到通过NSUserDefaults设置UserAgent的相干源码,再和最新的源码对比就能定位到改动的源码。
根据上篇文章的测试,极大概是在iOS 16.4发布(2023年3月27日发布)后,iOS 17发布(2023年9月18日发布)前改动的,所以先将源码切换到早于这个时间范围的提交应该是可行的。
不过呢,我喜欢先用UserAgent作为关键词搜索相干的汗青提交纪录,运气好的话能省很多事。在项目路径下执行下令:
  1. git log --since=2023-03-27 --until=2023-09-18 --grep=UserAgent --pretty=format:'%C(auto)%h - %s (%ad)' --date=iso
复制代码


  • --since和--until:指定提交时间范围
  • --grep:指定提交说明需要包含的字符串
  • --pretty: 自界说输特别式。%C(auto)会主动为输出添加颜色,%h是简写哈希值,%s是提交说明,%ad是作者提交日期
  • --date: 指定日期显示格式
除了用下令搜索,还可以用其他一些可视化软件(例如Sourcetree等),体验会更好点。运气不错,很快就定位到了:

这里增补一点,由于--date参数我没找到更好的显示选项,所以图中显示的时间是UTC-0700时区的,换算成北京时间(UTC+0800)需要加上15小时。
根据提交说明内里的链接,找到这个:
   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.
  简单概括就是:从NSUserDefault读取UA并覆盖的做法和现今的需求不符,需要删除这部分代码。
现在基本可以确定就是这个提交改动导致了当前的问题。用Xcode打开项目对比UserAgentIOS.mm文件提交,继续今后分析看看改了啥:

源码改动位置位于standardUserAgentWithApplicationName函数。
3. 对比源码

留意,以下关于源码的表明说明源于个人明确,仅供参考。
6a68b0c65d6c提交之前:
  1. if (auto override = dynamic_cf_cast<CFStringRef>(adoptCF(CFPreferencesCopyAppValue(CFSTR("UserAgent"), CFSTR("com.apple.WebFoundation")))))
  2.     return override.get();
复制代码
这段源码的作用就是从偏好配置中获取UserAgent的值,并实验将其动态转换为CFStringRef类型,如果转换成功(值不为空)便直接返回。
6a68b0c65d6c提交改动:
  1. if (!linkedOnOrAfterSDKWithBehavior(SDKAlignedBehavior::DoesNotOverrideUAFromNSUserDefault)) {
  2.     if (auto override = dynamic_cf_cast<CFStringRef>(adoptCF(CFPreferencesCopyAppValue(CFSTR("UserAgent"), CFSTR("com.apple.WebFoundation"))))) {
  3.         static BOOL hasLoggedDeprecationWarning = NO;
  4.         if (!hasLoggedDeprecationWarning) {
  5.             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.");
  6.             hasLoggedDeprecationWarning = YES;
  7.         }
  8.         return override.get();
  9.     }
  10. }
复制代码
相比改动前的源码,主要增加了linkedOnOrAfterSDKWithBehavior函数调用和过期告诫日志输出。
先说说过期告诫日志输出,这个逻辑很简单,因为hasLoggedDeprecationWarning是静态变量,所以只会在首次运行时输出一次。
再说说linkedOnOrAfterSDKWithBehavior函数,这个函数的作用是检查某个特定举动在当前应用程序链接的SDK版本上是否支持。函数入参DoesNotOverrideUAFromNSUserDefault这个特定举动,顾名思义,这举动就是不要从NSUserDefault覆盖UA。
那应用程序链接的SDK版本是什么呢?
开发iOS App时都会基于某个版本的iOS SDK开发,通常是基于Xcode内置的iOS SDK(位于/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/SDKs),这个版本就是链接的SDK版本。也就是说,如果你是用Xcode 15.1构建的应用程序,那么链接的SDK版本就是17.2;如果你是用Xcode 14.3.1构建的应用程序,那么链接的SDK版本就是16.4。更多关于Xcode内置的SDK版本信息,请看官方文档。
继续检察linkedOnOrAfterSDKWithBehavior的界说(位于WebKit项目/Source/WTF/wtf/cocoa/RuntimeApplicationChecksCocoa.cpp):
  1. bool linkedOnOrAfterSDKWithBehavior(SDKAlignedBehavior behavior)
  2. {
  3.     return sdkAlignedBehaviors().get(static_cast<size_t>(behavior));
  4. }
复制代码
这里还看不出什么,继续今后面找,可以在computeSDKAlignedBehaviors函数中找到根据链接SDK版本禁用特定举动的源码(以下省略部分源码):
  1. static SDKAlignedBehaviors computeSDKAlignedBehaviors()
  2. {
  3.     SDKAlignedBehaviors behaviors;
  4.     behaviors.setAll();
  5.     auto disableBehavior = [&] (SDKAlignedBehavior behavior) {
  6.         behaviors.clear(static_cast<size_t>(behavior));
  7.     };
  8.     ...
  9.    
  10.     if (linkedBefore(dyld_fall_2023_os_versions, DYLD_IOS_VERSION_17_0, DYLD_MACOSX_VERSION_14_0)) {
  11.         disableBehavior(SDKAlignedBehavior::FullySuspendsBackgroundContent);
  12.         disableBehavior(SDKAlignedBehavior::RunningBoardThrottling);
  13.         disableBehavior(SDKAlignedBehavior::PopoverAttributeEnabled);
  14.         disableBehavior(SDKAlignedBehavior::LiveRangeSelectionEnabledForAllApps);
  15.         disableBehavior(SDKAlignedBehavior::DoesNotOverrideUAFromNSUserDefault);
  16.     }
  17.     ...
  18.     return behaviors;
  19. }
复制代码
linkedBefore函数的作用就是判断当前应用程序链接的SDK是否小于入参中的指定版本,如果小于则返回true。
所以,现在可以明确知道当链接的SDK版本大等于iOS 17时,DoesNotOverrideUAFromNSUserDefault这个特定举动不会被禁用(是支持的),在这时判断条件!linkedOnOrAfterSDKWithBehavior(SDKAlignedBehavior:oesNotOverrideUAFromNSUserDefault)将不建立,也就不会从NSUserDefault覆盖UA!
分析到这,再总结一下基本结束了,但是总感觉少了些什么?在上篇文章中我的推测是:
   大概是WKWebView初始化时不再从NSUserDefaults获取默认值导致的问题
  咦?前面都没分析WKWebView,没有完备串起来,是不是初始化时获取的都还不确定。所以,别急着总结,先翻翻WKWebView类源码(位于WebKit项目/Source/WebKit/UIProcess/API/Cocoa/WKWebView.mm)。
在WKWebView类的初始化方法中发现了关于UserAgent的设置:
  1. - (void)_initializeWithConfiguration:(WKWebViewConfiguration *)configuration
  2. {
  3.     ...
  4.     _contentView = adoptNS([[WKContentView alloc] initWithFrame:self.bounds processPool:processPool configuration:pageConfiguration.copyRef() webView:self]);
  5.     _page = [_contentView page];
  6.    
  7.     ...
  8.     if (NSString *applicationNameForUserAgent = configuration.applicationNameForUserAgent)
  9.         _page->setApplicationNameForUserAgent(applicationNameForUserAgent);
  10.    
  11.     ...
  12. }
复制代码
不过,这是从WKWebViewConfiguration配置中获取applicationNameForUserAgent并设置。等等!这属性名称有点熟悉,这一看就是和前面源码改动位置所在的standardUserAgentWithApplicationName函数有关。找到WKContentView类中的page方法:
  1. - (WebKit::WebPageProxy*)page
  2. {
  3.     return _page.get();
  4. }
复制代码
继续找到WebPageProxy中的setApplicationNameForUserAgent函数:
  1. void WebPageProxy::setApplicationNameForUserAgent(const String& applicationName)
  2. {
  3.     if (m_applicationNameForUserAgent == applicationName)
  4.         return;
  5.     m_applicationNameForUserAgent = applicationName;
  6.     if (!m_customUserAgent.isEmpty())
  7.         return;
  8.     setUserAgent(standardUserAgent(m_applicationNameForUserAgent));
  9. }
复制代码
setUserAgent函数的作用是完成设置,而standardUserAgent函数的具体实现是区分平台的。继续找到WebPageProxyIOS.mm文件(位于WebKit项目/Source/WebKit/UIProcess/ios),standardUserAgent函数的具体实现如下:
  1. String WebPageProxy::standardUserAgent(const String& applicationNameForUserAgent)
  2. {
  3.     return standardUserAgentWithApplicationName(applicationNameForUserAgent);
  4. }
复制代码
这里调用的standardUserAgentWithApplicationName函数在iOS平台上的具体实现就是前面UserAgentIOS.mm文件中的同名函数,现在一切就都串起来了,推测是对的!
4. 分析总结

WebKit.framework是一个体系动态框架,已经内置在体系中,应用运行时加载。


  • 对于iOS 17以下的体系,WebKit.framework中还没有增加DoesNotOverrideUAFromNSUserDefault特定举动判断,不管是Xcode 15及以上还是15以下版本构建的应用,都还可以通过NSUserDefaults设置UserAgent。
  • 对于iOS 17及以上的体系,如果是Xcode 15及以上版本构建的应用,由于链接的SDK版本已经支持DoesNotOverrideUAFromNSUserDefault特定举动,所以通过NSUserDefaults设置UserAgent会失效;如果是Xcode 15以下版本构建的应用,由于链接的SDK版本低于iOS 17,DoesNotOverrideUAFromNSUserDefault特定举动会被禁用,所以还可以通过NSUserDefaults设置UserAgent,同时会输出过期告诫日志。
Xcode 15以下版本构建Xcode 15及以上版本构建iOS 17以下版本✅✅iOS 17及以上版本✅ + ⚠️❌ ✅:通过NSUserDefaults设置UserAgent有效
❌:通过NSUserDefaults设置UserAgent无效
⚠️:有过期告诫日志输出
解决方案

请看上篇文章中的解决方案。
如果你只需要设置一次,还可以参考后面增补内容内里的方法。
增补内容

1. UserAgent的组成

iOS 17.2模拟器获取的UserAgent:

  1. Mozilla/5.0 (iPhone; CPU iPhone OS 17_2 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/15E148
复制代码
以上UserAgent的组成大家应该基本看得懂,所以不再逐一赘述。让我感到困惑的是Mobile/15E148中的15E148,一开始以为是当前的体系版本,实验更换其他版本的体系获取,结果这个不停没变。
可以通过Mozilla/5.0或其他关键词在WebKit项目中全局搜索,找到以上UserAgent天生相干的源码(位于UserAgentIOS.mm文件的standardUserAgentWithApplicationName函数):
  1. String standardUserAgentWithApplicationName(const String& applicationName, const String& userAgentOSVersion, UserAgentType type)
  2. {
  3.     auto separator = applicationName.isEmpty() ? "" : " ";
  4.     if (type == UserAgentType::Desktop)
  5.         return makeString("Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko)", separator, applicationName);
  6. #if USE(STATIC_IPAD_USER_AGENT_VALUE)
  7.     UNUSED_PARAM(userAgentOSVersion);
  8.     UNUSED_PARAM(separator);
  9.     return makeString("Mozilla/5.0 (iPad; CPU OS 16_3_1 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/16.3 Mobile/15E148 Safari/604.1");
  10. #else
  11.     if (!linkedOnOrAfterSDKWithBehavior(SDKAlignedBehavior::DoesNotOverrideUAFromNSUserDefault)) {
  12.         if (auto override = dynamic_cf_cast<CFStringRef>(adoptCF(CFPreferencesCopyAppValue(CFSTR("UserAgent"), CFSTR("com.apple.WebFoundation"))))) {
  13.             static BOOL hasLoggedDeprecationWarning = NO;
  14.             if (!hasLoggedDeprecationWarning) {
  15.                 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.");
  16.                 hasLoggedDeprecationWarning = YES;
  17.             }
  18.             return override.get();
  19.         }
  20.     }
  21.     auto osVersion = userAgentOSVersion.isEmpty() ? systemMarketingVersionForUserAgentString() : userAgentOSVersion;
  22.     return makeString("Mozilla/5.0 (", deviceNameForUserAgent(), "; CPU ", osNameForUserAgent(), " ", osVersion, " like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko)", separator, applicationName);
  23. #endif
  24. }
复制代码
在前面的问题分析中已经分析了该函数关于当前问题的源码,再剔除其他平台相干的源码,可见末了的return语句是UserAgent天生的关键。和前面获取的UserAgent逐一对应:


  • deviceNameForUserAgent()对应iPhone,该函数在当前文件有界说
  • osNameForUserAgent()对应iPhone OS,该函数在当前文件有界说
  • osVersion对应17_2
  • applicationName对应Mobile/15E148。当applicationName为空时,分隔符separator为空字符串
由于applicationName是函数入参,所以现在需要知道函数是在哪调用的。根据前面问题分析可知,standardUserAgentWithApplicationName函数是在WKWebView类初始化时调用的,applicationName入参的值来自WKWebViewConfiguration类中的applicationNameForUserAgent方法(位于WebKit项目/Source/WebKit/UIProcess/API/Cocoa/WKWebViewConfiguration.mm):
  1. std::optional<RetainPtr<NSString>> _applicationNameForUserAgent;
  2. ...
  3. static NSString *defaultApplicationNameForUserAgent()
  4. {
  5. #if PLATFORM(IOS_FAMILY)
  6.     return @"Mobile/15E148";
  7. #else
  8.     return nil;
  9. #endif
  10. }
  11. ...
  12. - (NSString *)applicationNameForUserAgent
  13. {
  14.     return _applicationNameForUserAgent.value_or(defaultApplicationNameForUserAgent()).get();
  15. }
复制代码
value_or是C++中std:ptional类型的函数,该函数的作用就是如果_applicationNameForUserAgent为空则返回提供的默认值。
由此可见,Mobile/15E148竟然是硬编码的!如果在初始化WKWebView对象时,没有通过WKWebViewConfiguration对象设置applicationNameForUserAgent属性,那么将利用Mobile/15E148作为默认值返回。
那这个15E148有什么含义呢?在Xcode中选中return @"Mobile/15E148";这一行,然后右键选择[Show Last Change for Line],检察关于这行源码的上次改动信息:

   We noticed that we get the following default UA from a WKWebView on iOS using a sample app in the iPhone 6 simulator:
  Mozilla/5.0 (iPhone; CPU iPhone OS 12_1 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/16A342
  The default WKWebView UA should have a frozen OS build number, as we do in Safari.
  Mobile/16A342 -> Mobile/15E148.
  上面这段话来自192809 - WKWebView default UA doesn’t freeze the build number页面。简单概括就是WKWebView的UA应该和Safari一样,固定一个体系构建版本号。
再具体看看源码改动对比:

从改动对比可知,原先是通过[UIDevice currentDevice].buildVersion动态获取体系构建版本号,后续才固定为15E148这个版本号。这里有几个疑问:

  • 找不到buildVersion方法?
通常应用开发者只能通过systemVersion获取体系版本(例如17.2),buildVersion是私有API,更多详情可以参考UIKitSPI.h文件(SPI即System Programming Interface,体系级编程接口),如果找不到,大概是当前提交已经移除了相干源码,请切换到更早的提交。

  • 15E148具体是哪个体系版本的构建版本号?
官方文档中没找到体系构建版本号相干的列表,不过找到了这个网站Xcode Releases。由于这是以Xcode版本为主的网站,所以iOS相干的版本数据也不是很全,例如在Xcode可以看到iOS 17.0.1的构建版本号是21A342:

这个版本在该网站找不到,不过好在这个构建版本号是递增的,最终可以明确15E148对应的体系版本介于iOS 11.2(15C107)和iOS 11.3(15E217)之间。

  • 为什么要固定体系构建版本号?
我没有找到官方说明或表明,以下个人推测仅供参考:
iOS 11和iPhone X同一年发布,iPhone X带来刘海屏的同时,iOS 11也带来了新的网页特性用于适配安全区域,再今后感觉也没有什么新的特性需要网页适配。那么,为了方便开发者根据版本对网页举行适配,将UA中的体系构建版本号固定为15E148倒也合理。
2. UserAgent的设置优先级

UserAgent设置的三种方式:


  • NSUserDefaults方式:在WKWebView对象初始化前,通过registerDefaults方法设置,一次设置全局生效,已过期
  • applicationNameForUserAgent方式:在WKWebView对象初始化时,通过WKWebViewConfiguration对象设置,后续再修改无效
  • customUserAgent方式:在WKWebView对象初始化后,直接赋值设置,支持动态修改
如果三种方式同时设置,结合之前的分析,可知优先级如下:
customUserAgent方式 > NSUserDefaults方式 > applicationNameForUserAgent方式
现阶段NSUserDefaults方式已过期,如果你只需要设置一次,那么建议通过applicationNameForUserAgent方式设置。不过,这里需要留意一点,请不要像下面例子般直接赋值:
  1. let webViewConfiguration = WKWebViewConfiguration()
  2. webViewConfiguration.applicationNameForUserAgent = "App/1.0.0"
  3. webView = WKWebView(frame: view.bounds, configuration: webViewConfiguration)
复制代码
如许会出现默认值Mobile/15E148被替换的情况(原因请看前面的分析):
  1. Mozilla/5.0 (iPhone; CPU iPhone OS 17_2 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) App/1.0.0
复制代码
UA中缺失Mobile/15E148会导致一些网页无法正常适配,特别是Mobile这部分,很多网页会根据这个判断是不是属于移动端。所以,可以参考下面的例子先获取默认值拼接成新的再设置:
  1. let webViewConfiguration = WKWebViewConfiguration()
  2. webViewConfiguration.applicationNameForUserAgent = "\(webViewConfiguration.applicationNameForUserAgent ?? "") App/1.0.0"
  3. webView = WKWebView(frame: view.bounds, configuration: webViewConfiguration)
复制代码
设置后效果:
  1. Mozilla/5.0 (iPhone; CPU iPhone OS 17_2 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/15E148
  2. App/1.0.0
复制代码
末了

如果这篇文章对你有所帮助,点赞

本帖子中包含更多资源

您需要 登录 才可以下载或查看,没有账号?立即注册

x
回复

使用道具 举报

0 个回复

倒序浏览

快速回复

您需要登录后才可以回帖 登录 or 立即注册

本版积分规则

锦通

论坛元老
这个人很懒什么都没写!
快速回复 返回顶部 返回列表