简体   繁体   English

如何访问在“项目”>“构建设置”>“其他Swift标志”中定义的值?

[英]How to access a value defined in Project > Build Settings > Other Swift Flags?

I have a value in Other Swift Flags -DSERVER_IP=${SERVER_IP} linked to a Build Phase > Run Script: export SERVER_IP='ipconfig getifaddr en0' 我在链接到构建阶段>运行脚本的其他Swift标志-DSERVER_IP=${SERVER_IP}有一个值: export SERVER_IP='ipconfig getifaddr en0'

How do I access the value of SERVER_IP from a ViewController or a swift file and use it to populate a variable in swift? 如何从ViewController或swift文件访问SERVER_IP的值,并使用它在swift中填充变量? Something like let currentIP = SERVER_IP 诸如let currentIP = SERVER_IP类的东西

Build settings use environment variables that exist at the time the build start, which is before your build phase runs. 构建设置使用在构建开始时(在构建阶段运行之前)存在的环境变量。 Due to this, SERVER_IP will be empty while Xcode is doing its the build phase (exported variables are not available to other build phases). 因此,当Xcode执行其构建阶段时, SERVER_IP将为空(导出的变量对其他构建阶段不可用)。

There is a workaround, though. 不过,有一种解决方法。 You can add a new Swift file to the project, let's call it generated-stuff.swift , and have the run script output the information there: 您可以将一个新的Swift文件添加到项目中,我们将其命名为generated-stuff.swift ,然后让运行脚本在其中输出信息:

echo 'let SERVER_IP="'`ipconfig getifaddr en0`'"' > MyProject/generated-stuff.swift

The above will generate a file like with the following contents: 上面将生成一个类似以下内容的文件:

let SERVER_IP="1.2.3.4"

You'll then be able to use the variable in your project. 然后,您将可以在项目中使用该变量。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM