在Xcode的构建时添加变量 [英] Adding variables at build time in Xcode
问题描述
我需要根据在Xcode中执行的构建类型来更改一些动态值.
I have some dynamic values I need to change based on the type of build I am doing in Xcode.
我创建了两个方案DEV
和PROD
,并在每个方案中设置了环境变量
I have created 2 schemes DEV
and PROD
and set environment variables in each
然后我在代码中按如下方式使用这些
I then consume these in code as follows
var serviceDomain: String {
let envVar = ProcessInfo.processInfo.environment
guard let value = envVar["APP_SERVICE_DOMAIN"] else { fatalError("Missing APP_SERVICE_DOMAIN enviroment variable") }
return value
}
这是解决这个问题的正确方法吗?
Is this the correct way to approach this?
一旦编译了应用程序,这些值现在应该与它捆绑在一起吗?
Once an app is compiled, should these values now be bundled with it?
我遇到的问题是,一旦停止模拟器,如果尝试打开以这种方式构建的应用程序,它将崩溃,并且我怀疑环境变量不再存在.
I have an issue in that once I've stopped my simulator, if I try to open an app built this way, it crashes and I suspect the environment variables aren't present anymore.
简而言之,我想要一个使用一组变量的开发人员构建以及一个使用另一组变量的发行/生产版本.
推荐答案
您根本不需要环境变量!
You don't need environment variables at all!
转到构建设置并搜索活动的编译条件:
Go to build settings and search for active compilation conditions:
像我在此处所做的那样,为调试添加DEBUG
,为发布添加RELEASE
.
Add DEBUG
for Debug and RELEASE
for Release as I have done here.
然后声明您的变量.假设您希望a
在发布模式下为1,在调试模式下为2,
Then declare your variables. Let's say you want a
to be 1 in release mode, and 2 in debug mode,
#if RELEASE
let a = 1
#elseif DEBUG
let a = 2
#endif
就是这样!
根据方案的构建配置",编译器将选择要编译的值之一.这里是调试,因此将使用2:
The compiler will choose one of the values to compile, depending on your scheme's Build Configuration. Here, it is debug, so 2 will be used:
这篇关于在Xcode的构建时添加变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!