是否可以仅针对调试环境在 iOS 9 中禁用 ATS?

Is it possible to disable ATS in iOS 9 just for debug environment?

我正在开发没有 HTTPS 设置的开发环境。是否可以仅针对开发(调试)模式自动禁用 ATS?

是的,您可以将项目设置配置为使用不同的 Info.plist 文件进行调试、发布或您在项目中使用的任何配置(类似于设置配置文件的方式),因此在您的调试 plist 中你可以完全禁用 ATS。

转到项目 -> 你的目标 -> 构建设置 -> Info.plist 文件

我的解决方案是将 ATS 禁用选项保持为默认的 NO 值,并添加一个新的 运行 脚本阶段以在构建应用程序时在应用程序包的 Info.plist 中更改它。

这是脚本:

#Disables ATS in debug builds.
INFOPLIST="${TARGET_BUILD_DIR}"/"${INFOPLIST_PATH}"
case "${CONFIGURATION}" in
"Release"|"Adhoc")
/usr/libexec/PlistBuddy -c "Set :NSAppTransportSecurity:NSAllowsArbitraryLoads NO" "${INFOPLIST}"
;;
"Debug")
/usr/libexec/PlistBuddy -c "Set :NSAppTransportSecurity:NSAllowsArbitraryLoads YES" "${INFOPLIST}"
;; 
esac

另一个解决方案。通过使用 INFOPLIST_PREPROCESS = YESINFOPLIST_PREPROCESSOR_DEFINITIONS = DEBUG=1

可以直接在Info.plist.

中使用#ifdef#if像C代码一样进行条件预处理
<key>UIMainStoryboardFile</key>
<string>Main</string>
#if DEBUG
<key>NSAppTransportSecurity</key>
<dict>
    <key>NSAllowsArbitraryLoads</key>
    <true/>
</dict>
#endif
<key>UIRequiredDeviceCapabilities</key>
<array>

缺点:无法打开 Xcode 的 属性 列表编辑器,因为它的格式不正确 XML :(

我已经根据上述方法制定了解决方案,但在 git 回购协议中工作顺利。这个想法是为发布配置维护原始的 Info.plist,唯一的区别是 NSAllowsArbitraryLoads 中的 Debug 在构建时自动生成。

我的Xcode版本是11.3.1。只需 3 个简单步骤:

  1. Build settings - Packaging - Info.plist 为 Debug 配置添加 Info.debug.plist文件:

  1. 构建阶段添加此运行脚本
    # Disables ATS in debug configuration
    if [ "${CONFIGURATION}" = "Debug" ]; then
        plist=$PRODUCT_SETTINGS_PATH
        src="`dirname $plist`/Info.plist"
        cp -f $src $plist
        /usr/libexec/PlistBuddy -c "Set :NSAppTransportSecurity:NSAllowsArbitraryLoads YES" "${plist}"
    fi

  1. Info.debug.plist放到。git忽略:

echo Info.debug.plist >> .gitignore