iOS 预处理宏打包脚本编写
2022-06-16 本文已影响0人
anny_4243
开发过程中遇到了一个需求,需要隐项目中VPN相关的代码,而是否隐藏需要在自动化打包时进行可选配置。需要用到条件编译,而条件编译的条件只能是常量,所以需要在打包时就把这个条件写进Xcode的配置项里面,这样才能变成常量。
image.pngiOS中条件编译时用到的常量可以使用预处理宏,在Xcode存放中存放的位置如图所示,我们只需要用脚本写入即可。
首先需要读取plist文件中在打包平台填写的VPN是否开启的常量值,然后把这个常量值写入预处理宏,用到了ruby脚本。
shell脚本部分代码:
#当前项目根目录
project_path=$(cd `dirname $0`; pwd)
echo "当前项目根目录=$project_path"
#进入当前目录
cd $project_path
# VPN
export openSXFVPN=`/usr/libexec/PlistBuddy -c "Print data:openSXFVpn" $project_path/config.plist`
if [ $openSXFVPN = "true" ] ;then
sed -i '' "s/gcc_arr.push(\'VPNOpen=.*\')/gcc_arr.push(\'VPNOpen=1\')/" $project_path/VPN.rb
else
sed -i '' "s/gcc_arr.push(\'VPNOpen=.*\')/gcc_arr.push(\'VPNOpen=0\')/" $project_path/VPN.rb
fi
ruby VPN.rb
VPN.rb:
require 'xcodeproj'
# 打开工程
project_path = './SWSuperApp.xcodeproj'
project = Xcodeproj::Project.open(project_path)
# 查询有多少个target
project.targets.each do |target|
puts target.name
end
# 遍历配置
project.targets[0].build_configurations.each do |config|
puts config.name
build_settings = config.build_settings
build_settings.each do |key, value|
print key, " == ", value, "\n"
end
end
# 找到需要操作的target,我这里只有一个target
target_index = 0
project.targets.each_with_index do |target, index|
if target.name == "SWSuperApp"
target_index = index
puts target_index
end
end
target = project.targets[target_index]
def check_repeat_element(gcc_preprocess, repeat_ele)
if gcc_preprocess
gcc_preprocess.each do |gcc|
if gcc.start_with?(repeat_ele)
return true
end
end
end
return false
end
def delete_repeat_element(gcc_preprocess, repeat_ele)
if gcc_preprocess
gcc_preprocess.each do |gcc|
if gcc.start_with?(repeat_ele)
gcc_preprocess.delete(gcc)
end
end
end
end
build_config_preprocess = ''
# 遍历配置
target.build_configurations.each do |config|
gcc_preprocess = config.build_settings['GCC_PREPROCESSOR_DEFINITIONS']
gcc_arr = Array.new()
if gcc_preprocess.is_a? String
gcc_arr.push(gcc_preprocess);
elsif gcc_preprocess.is_a? Array
gcc_arr = gcc_preprocess
end
if check_repeat_element(gcc_arr, '$(inherited)')
delete_repeat_element(gcc_arr, '$(inherited)')
end
if check_repeat_element(gcc_arr, 'VPNOpen')
delete_repeat_element(gcc_arr, 'VPNOpen')
end
gcc_arr.push('$(inherited)')
gcc_arr.push('VPNOpen=0')
config.build_settings['GCC_PREPROCESSOR_DEFINITIONS'] = gcc_arr
build_config_preprocess = gcc_arr
end
puts '修改编译配置完成 ' + build_config_preprocess.to_s
project.save