We have these environment variables
within the Xcode Scheme
Which works well locally with this code
let webHost = ProcessInfo.processInfo.environment["HOST_URL"]!
let apiHost = ProcessInfo.processInfo.environment["API_URL"]!
let beamsKey = ProcessInfo.processInfo.environment["BEAMS_KEY"]!
let mixpanelKey = ProcessInfo.processInfo.environment["MIXPANEL_KEY"]!
However, when deploying using Xcode Cloud with the same environment variables
.
It succeeds in building, but the app crashes with this log.
What is the right way to read these environment variables when using Xcode Cloud?
3
Answers
These variables are available and valid while the temporary environment is active to build the app only, not when the app is running on the device.
The environment variables can, however, be “captured” during the build process using shell scripts (see the Xcode "Build Phases" under the target settings or the Xcode Cloud custom build scripts).
Another good solution is to use some code generation tool like Arkana. This tool creates obfuscated code to make the variables available at the runtime eventually.
Again the tool or shell script must run in the Xcode Cloud environment. The steps to do this are out of the scope of this response.
I had a similar issue, mostly i wanted to add an
api-key
in the project without this exist in the source code. So I had to create aci_pre_xcodebuild.sh
fileand in the code we have
So, this was an absolute headache but I finally figured out a satisfactory way to access and use these variables in code.
My solution uses:
ci_pre_xcodebuild.sh
file to write the environment variables in the JSONStep 1: Basic JSON file
Secrets.json
(at: YourProject/SupportingFiles/secrets.json)
Step 2: Write the variables in Xcode Cloud
In this screenshot you can see that I’ve duplicated the keys for different environments. I didn’t expand on this for the sake of brevity, but you can definitely have different secrets JSON files for different Xcode Scheme configurations.
Step 3: Add a
ci_pre_xcodebuild.sh
fileImportant: the name of the files and their position matter.
The goal here is to add a script that the CI (Xcode Cloud) will execute each time it builds. In this script, we’re going to create and fill our JSON.
In this group, add a new file called
ci_pre_xcodebuild.sh
Write the following:
Of course, you need to change this text depending on your keys and the location of the file. I added a few keys as an example.
chmod +x ci_pre_xcodebuild.sh
. This fixes a warning in Xcode Cloud.Step 4: [BONUS] A simple Swift file to access the environment variables