原文 https://buildingvts.com/launch-multiple-ios-simulators-on-a-single-compile-985fd2ad5eb1
当你写完自动布局需要测试在不同模拟器上的运行效果时你是否很头疼,需要一个一个模拟器去启动运行。
这时候如果可以一编译就同时启动多个模拟器那该是多么好啊。XCode 9 有一个新的特性——允许多个模拟器共存。当然,它不会编译一次同时启动多个模拟器,这需要我们自己写一点脚本去控制。
具体的步骤如下:
0x01
在 XCode 中,点击Edit Scheme...
,在Build
选项下的Pre-actions
卡下选择+
按钮新增一个Custom Simulators
custom_sim=`xcrun simctl list | grep 'Custom Simulators' | awk -F'[()]' '{print $2}'`
if [ -z "${custom_sim}" ]; then
xcrun simctl create Custom\ Simulators com.apple.CoreSimulator.SimDeviceType.iPhone-X com.apple.CoreSimulator.SimRuntime.iOS-11-2
fi
pre-action
脚本创建了一个类型为iOS 11.2 的 iPhone X 模拟器 Custom Simulators
,如果你当前的环境中没有该选项,build 一下你的工程,你就能够在模拟器的下拉选项列表里面看到这个了。
0x02
在你的工程根目录下创建一个名为MultiSimConfig.txt
的文件,这个文件指定了 “Custom Simulators” 应该启动哪些模拟器。
想知道你的 XCode 环境中支持哪些模拟器,可以在Terminal
中运行如下命令:
instruments -s devices
类似的,MultiSimConfig.txt 可以这样写:
iPhone 6 (11.2)
iPhone 8 Plus (11.2)
iPhone X (11.2)
0x03
创建一个脚本launch_multiple_simulators.sh
去读取 MultiSimConfig.txt 并启动里面指定的模拟器。
#!/bin/bash
xcrun simctl shutdown all
path=$(find ~/Library/Developer/Xcode/DerivedData/${project_name}-*/Build/Products/Debug-iphonesimulator -name "${app_name}.app" | head -n 1)
echo "${path}"
filename=${path_to_MultiSimConfig.txt}
grep -v '^#' $filename | while read -r line
do
echo $line
把上面这个脚本放到工程根目录下。用你工程名字替换${project_name}
,app 名字替换${app_name}
(一般来说工程名字和app名字是一样的),最后用你项目的 bundle identifier 替换${bundle_identifier}
这个。该脚本运行的时候会把打开的模拟器关闭,定位到 derived data 目录下的执行文件,然后读取 MultiSimConfig.txt 文件,最后安装 app 到指定的模拟器并启动。
0x004
最后一步是将项目跟我们写好的脚步关联起来。
选择项目的 target -> Build Phases
-> New RunScript Phase
,新增一个自定义执行脚本
custom_sim=`xcrun simctl list | grep 'Custom Simulators' | awk -F'[()]' '{print $2}'`
if [ ! -z "${custom_sim}" ] && [ "${TARGET_DEVICE_IDENTIFIER}" = "${custom_sim}" ]; then
/bin/sh launch_multiple_simulators.sh
fi
这段脚本将“Custom Simulators”的 UUID 保存到 custom_sim
变量,紧接着如果当前的 target 设备跟 “Custom Simulators” 的UUID匹配的话就执行launch_multiple_simulators.h
脚本。
项目地址如下:
https://github.com/ginowu7/CustomSimulatorsExample
编译运行,效果如下